给定以下两个表和关系:
模型容器:id、name、desc、created_at、updated_at
public function items()
{
return $this->hasMany('App\Models\Items', 'container_id', 'id');
}
模型项:id、container_id、type_id、name、created_at、updated_at
public 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();
}
...并查看特定容器中的特定项目而无需执行更讨厌的操作,例如:
//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关系——通过引用容器的名称来实现这一点,这样我就可以在Items::find($containerName)不更改模型中的primaryKey字段的情况下做到这一点。