为了账号安全,请及时绑定邮箱和手机立即绑定

使用与 slug 而不是关系 id 的belongsTo 雄辩的关系

使用与 slug 而不是关系 id 的belongsTo 雄辩的关系

PHP
阿晨1998 2021-06-30 09:43:39
给定以下两个表和关系:模型容器:id、name、desc、created_at、updated_atpublic function items(){    return $this->hasMany('App\Models\Items', 'container_id', 'id');}模型项: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();}...并查看特定容器中的特定项目而无需执行更讨厌的操作,例如://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字段的情况下做到这一点。
查看完整描述

1 回答

  • 1 回答
  • 0 关注
  • 126 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信