Laravel雄辩ORM关系命名约定 [英] 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 Eloquent {
public function author()
{
return $ this-> belongsTo('Author');
}
}
$ books = Book :: all()
foreach($ books as $ book){
echo $书本 - >作者 - >姓名;
}
class Book extends Eloquent {
public function author()
{
return $this->belongsTo('Author');
}
}
$books = Book::all()
foreach ($books as $book) {
echo $book->author->firstname;
}
在上面的例子中,我必须调用这个方法或者我可以命名其他东西吗?我尝试将其命名为别的东西(只是出于好奇),但它返回null,因此错误试图获取非对象的属性。
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".
编辑:通过将外键传递给belongsTo,使其工作,如下所示:
I got it to work by passing the foreign key to belongsTo, like this:
class Book扩展Eloquent {
class Book extends Eloquent {
public function daauthor()
{
return $this->belongsTo('Author', 'author_id');
}
}
$book = Book::find(55);
dd($book->daauthor);
有人可以解释为什么吗?
Can someone explain why?
推荐答案
方法 belongsTo 尝试确定链接到<em>作者模型的属性。要实现这个Laravel使用调用者的函数名称。
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.
所以在你的代码中,Laravel看到了 daauthor 函数,并尝试使用属性 daauthor_id 在图书表格中,以完全满足您的要求。因为你的书籍表没有这个属性,它将失败。
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.
通过在方法中设置$ foreignKey可以覆盖默认行为:
By setting the $foreignKey on the method you can override the default behaviour:
public function daauthor()
{
return $this->belongsTo('Author', 'author_id');
}
有关详细信息,请查看 \Illuminate\\的源代码\\ Database\Eloquent\Model 。
For more details check out the source code of \Illuminate\Database\Eloquent\Model.
这篇关于Laravel雄辩ORM关系命名约定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!