Laravel hasMany and belongsTo parameters

后端 未结 2 1816
梦毁少年i
梦毁少年i 2020-12-14 04:15

I have a table store, and store has many libraries, in library I have foreign key of store store_id.

Store table

id(PK)

L

2条回答
  •  粉色の甜心
    2020-12-14 05:06

    Try this one. It works. Add this to your model.

    Library model

    public function store()
        {
            return $this->belongsTo(Store::class, 'store_id', 'id');
        }
    

    Store model

     public function libraries()
        {
            return $this->hasMany(Library::class);
        }
    

    example code.

     $store = Store::find(1);
     dd($store->libraries);
    

    Because in this case a store has many libraries, the Store model has a libraries() function. Refer to last line of James' answer for more information on this standard.

提交回复
热议问题