Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Eloquent ORM relationship naming conventions

When defining an inverse relation in Eloquent, do you have to name your dynamic property the same as your related model?

class Book extends Eloquent {

    public function author()
    {
        return $this->belongsTo('Author');
    }

}

$books = Book::all()
foreach ($books as $book) {
    echo $book->author->firstname;
}

In the above example, do I have to call this method author or can I name it something else? I tried to name it to something else (just out of curiosity) but it then returns null hence the errors "Trying to get property of non-object".

EDIT: I got it to work by passing the foreign key to belongsTo, like this:

class Book extends Eloquent {

    public function daauthor()
    {
        return $this->belongsTo('Author', 'author_id');
    }

}

$book = Book::find(55);
dd($book->daauthor);

Can someone explain why?

like image 310
iamdtang Avatar asked Feb 13 '14 09:02

iamdtang


1 Answers

The method belongsTo tries to determine the attribute which links to the Author model. To accomplish this Laravel uses the function name of the caller.

So in your code Laravel sees the daauthor function and tries to use the attribute daauthor_id in the books table to fully your request. As your books table does not have this attribute it fails.

By setting the $foreignKey on the method you can override the default behaviour:

public function daauthor()
{
    return $this->belongsTo('Author', 'author_id');
}

For more details check out the source code of \Illuminate\Database\Eloquent\Model.

like image 112
maxwilms Avatar answered Sep 28 '22 20:09

maxwilms