简体   繁体   中英

Laravel Eloquent ORM relationship definition

I have models Clearance and Item

every clearance has a specific item, but more than one clearance can have the same item. Structurally, this just means Clearance has an item_id column.

So in the models I have defined clearance as hasOne('Item'); and item as belongsToMany('Clearance')

but when I call item, it gives me the error clearance_item doesn't exist, so I think I must have defined the relationship wrong. I try with belongsTo (assuming that many will trigger wanting a join table), and I get things back, but not the items don't have the clearances in the return data

Perhaps it should be:

class Clearance extends Eloquent
{
 public function item()
 {
   return $this->belongsTo('Item');
 }

}

class Item extends Eloquent
{
 public function clearances()
 {
    return $this->hasMany('Clearance');
 }
}

Have you tried this? You can also go through the docs again to see how relationships are defined

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