我有一本书桌和作者。我希望能够将作者与书籍联系起来。我调整了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';
}
}
}
答案 0 :(得分:2)
模特图书
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/