給定以下兩個表和關(guān)系:模型容器:id、name、desc、created_at、updated_atpublic function items(){ return $this->hasMany('App\Models\Items', 'container_id', 'id');}模型項(xiàng):id、container_id、type_id、name、created_at、updated_atpublic function containers(){ return $this->belongsTo('App\Models\Containers', 'id', 'container_id');}我怎樣才能得到所有items屬于container我所擁有的一切container:name而不必做類似的事情://Route::get('/api/v1/containers/{container}/items', 'ItemsController@index'); public function index($container){ //Show all items in a specific container return Containers::where('name', $container) ->firstOrFail() ->items() ->get() ->toJson();}...并查看特定容器中的特定項(xiàng)目而無需執(zhí)行更討厭的操作,例如://Route::get('/api/v1/containers/{container}/items/{item}', 'ItemsController@show');public function show($container, $item){ //Show specific item in a specific container return Containers::where('name', $container) ->firstOrFail() ->items() ->where('id', $item) ->firstOrFail() ->toJson();}在這種情況下,我只將容器名稱作為 URL 友好的 slug 并幫助阻止 URL 操作。有沒有辦法——即使它是次要的belongsTo關(guān)系——通過引用容器的名稱來實(shí)現(xiàn)這一點(diǎn),這樣我就可以在Items::find($containerName)不更改模型中的primaryKey字段的情況下做到這一點(diǎn)。
- 1 回答
- 0 關(guān)注
- 135 瀏覽
添加回答
舉報(bào)
0/150
提交
取消