简体   繁体   中英

Laravel Eloquent belongsTo not working

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 object property ( public $main_page )
  • GetAccessor ( $page->getMainPage() )
  • Table column/attribute ( $page->attributes['main_page'] )
  • Attribute/column from table ( $this->attributes['main_page'] )
  • Loaded relation ( $this->relations['main_page'] )
  • Unloaded relation ( $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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM