I can't make the belongsTo
relationship work (or I am using wrong relationship).
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.
In the Page
model I have the following:
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
. 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. But you already have a column name main_image
. So you should either rename the attribut (column name) or the relation. I would rename the column to main_image_id
.
The priority/order of what is to be returned is:
public $main_page
) $page->getMainPage()
) $page->attributes['main_page']
) $this->attributes['main_page']
) $this->relations['main_page']
) $this->main_page()->get()
)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.