Reputation: 361
I have a couple of tables like so:
Authors Table - id - book_id - name
Books Table - id - ref - author - title
The ref on the books table is the same as the book_id on the authors table, but i can't seem to get the authors books by doing this in my view:
{{ $author->books->first()->title }}
My models for authors and books look like so:
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');
}
}
Really need some help on this please.
Upvotes: 0
Views: 1879
Reputation: 2991
You can pass the foreign key and local key in hasMany
but it looks like you're passing author
as the foreign key and name
as the local key. It should be ref
for the foreign key and book_id
for the local key.
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');
}
}
Upvotes: 1