[英]Laravel Eloquent belongsTo not working
I can't make the belongsTo
relationship work (or I am using wrong relationship). 我不能使belongsTo
关系工作(或我使用错误的关系)。
My database structure (simplified): 我的数据库结构(简化):
pages : 页面 :
id | title | main_image ----------------------- 1 | Test | 5
media : 媒体 :
id | filepath ----------------------- 5 | uploads/test.jpg
So I want to be able to do $page->main_image
and it would return me instance of the Media model, so I could use $page->main_image->filepath
etc. 所以我希望能够做$page->main_image
,它会返回我的Media模型实例,所以我可以使用$page->main_image->filepath
等。
In the Page
model I have the following: 在Page
模型中,我有以下内容:
public function main_image()
{
return $this->belongsTo('App\Modules\Media\Models\Media', 'id', 'main_image');
}
But when I do $page->main_image
I just get int 5
. 但是当我执行$page->main_image
我只得到了int 5
。 Am I using the wrong relationship here? 我在这里使用了错误的关系吗?
Thanks! 谢谢!
When accessing $page->main_image
Eloquent will only try to find the main_image()
relation if there is no attribute with the same name. 访问$page->main_image
如果没有相同名称的属性, $page->main_image
将只尝试查找main_image()
关系。 But you already have a column name main_image
. 但是你已经有了一个名称main_image
。 So you should either rename the attribut (column name) or the relation. 因此,您应该重命名attribut(列名称)或关系。 I would rename the column to main_image_id
. 我会将列重命名为main_image_id
。
The priority/order of what is to be returned is: 要返回的优先级/顺序是:
public $main_page
) 公共对象属性( public $main_page
) $page->getMainPage()
) GetAccessor( $page->getMainPage()
) $page->attributes['main_page']
) 表列/属性( $page->attributes['main_page']
) $this->attributes['main_page']
) 表中的属性/列( $this->attributes['main_page']
) $this->relations['main_page']
) 加载关系( $this->relations['main_page']
) $this->main_page()->get()
) 卸载关系( $this->main_page()->get()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.