【问题标题】:Laravel Voyager: BelongsToManyLaravel Voyager:属于多多
【发布时间】:2017-12-16 06:47:52
【问题描述】:

我有一个表书籍和作者。我想获得将作者附加到书籍的能力。我为书籍调整 BREAD:

通过这些设置,我可以单击编辑并为我的书选择作者,但是当我尝试保存书籍时,laravel 会出现此错误:

 SQLSTATE[HY000]: General error: 1366 Incorrect integer value: 'Mrs. Alivia 
 Stanton IV' for column 'authors_id' at row 1 (SQL: insert into 
 `authors_books` (`authors_id`, `books_id`) values (Mrs. Alivia Stanton IV, 
 55))

这是合乎逻辑的。但是当我将name 切换到id 时,laravel 给出了这个错误:

 SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in field 
 list is ambiguous (SQL: select `id` from `authors` inner join 
 `authors_books` on `authors`.`id` = `authors_books`.`authors_id` where 
  `authors_books`.`books_id` = 57) (View: 

我尝试使用所有组合,但没有任何反应。

示范书:

class Books extends Model
{   
protected $fillable = ['name','img'];

public function authors()
{
    return $this->belongsToMany('App\Authors');
}

public function getImgAttribute($img)
{   
    if(!empty($img)){
        return 'storage/images/books/'.$img;
    }else{
        return 'storage/images/books/not-found.jpg';
    }
}

 }

模型作者:

class Authors extends Model
 {

protected $fillable = ['name','img'];

public function books()
{
    return $this->belongsToMany('App\Books');
}

public function getImgAttribute($img)
{   
    if(!empty($img)){
        return 'storage/images/authors/'.$img;
    }else{
        return 'storage/images/books/not-found.jpg';
    }
}
}

请帮忙!

【问题讨论】:

  • 请在将作者附加到您的图书时提供您的代码。
  • 选择id时需要指定表,所以应该是:select 'authors.id' from 'authors' [...]
  • @dexterb 模型设置正确,因为站点工作正常,航海者出现问题,但我为你插入模型代码
  • 你能包括你用什么方法来附加吗?因为你可以做$author->books()->save($book) 和 $author->books()->attach($book->id)`
  • 你为什么用windows xp?

标签: php laravel laravel-5 voyager


【解决方案1】:

示范书:

class Books extends Model
{   
protected $fillable = ['name','img'];

public function authors()
{
    return $this->belongsToMany('App\Author','Pivot table');
}

public function getImgAttribute($img)
{   
    if(!empty($img)){
        return 'storage/images/books/'.$img;
    }else{
        return 'storage/images/books/not-found.jpg';
    }
}

 }

模型作者:

class Authors extends Model
 {

protected $fillable = ['name','img'];

public function books()
{
    return $this->belongsToMany('App\Book,'Pivot table');
}

public function getImgAttribute($img)
{   
    if(!empty($img)){
        return 'storage/images/authors/'.$img;
    }else{
        return 'storage/images/books/not-found.jpg';
    }
}
}

请阅读此文档以更好地理解http://laraveldaily.com/pivot-tables-and-many-to-many-relationships/

【讨论】:

  • 真的吗?我说:该站点运行良好。根据文档:我无法指定绑定表,除了您编写的代码无法正常工作外,第二个参数是数据透视表,而不是字段。请阅读此文档以更好地理解laraveldaily.com/pivot-tables-and-many-to-many-relationships
  • NONAME 我很抱歉。我的坏
猜你喜欢
  • 2019-05-06
  • 2023-04-07
  • 2018-11-27
  • 2022-01-23
  • 2020-12-19
  • 2014-07-19
  • 2020-10-07
  • 2020-01-21
  • 2021-05-10
相关资源
最近更新 更多