我有几张像这样的表:
作者表 - ID - book_id - 姓名
书籍表 - ID - 参考 - 作者 - 标题
books表上的ref与authors表上的book_id相同,但在我看来,我似乎无法通过这样做来获取作者的书籍:
{{ $author->books->first()->title }}
我的作者和书籍模型如下:
class Authors extends \Eloquent {
protected $guarded = ['id'];
public $table = 'authors';
public $timestamps = false;
public function books()
{
return $this->hasMany('Books', "author","name");
}
}
class Books extends \Eloquent {
protected $guarded = ['id'];
public $timestamps = false;
public function author()
{
return $this->hasOne('Authors');
}
public function categories(){
return $this->hasMany('Categories');
}
}
请真的需要一些帮助。
答案 0 :(得分:1)
您可以在hasMany
中传递外键和本地密钥,但看起来您将author
作为外键并将name
作为本地密钥传递。外键应为ref
,本地密钥为book_id
。
class Authors extends \Eloquent {
protected $guarded = ['id'];
public $table = 'authors';
public $timestamps = false;
public function books()
{
return $this->hasMany('Books', "ref", "book_id");
}
}
class Books extends \Eloquent {
protected $guarded = ['id'];
public $timestamps = false;
public function author()
{
return $this->hasOne('Authors');
}
public function categories(){
return $this->hasMany('Categories');
}
}