Laravel 有两个可能的数据透视表的雄辩资源-返回值的优雅方式
我有一个资源,它有两个可能的支点。现在,我想根据加载的轴添加值 我现在就是这样做的:Laravel 有两个可能的数据透视表的雄辩资源-返回值的优雅方式,laravel,eloquent,laravel-6,laravel-resource,Laravel,Eloquent,Laravel 6,Laravel Resource,我有一个资源,它有两个可能的支点。现在,我想根据加载的轴添加值 我现在就是这样做的: <?php namespace App\Http\Resources; use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\PotentiallyMissing; class CarAttributeResource extends JsonResource { /** *
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\PotentiallyMissing;
class CarAttributeResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
*
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'title' => ($title
= $this->whenPivotLoaded('car_car_attribute',
function () {
return (boolean)$this->pivot->custom === true
? $this->pivot->title : $this->title;
})) instanceof PotentiallyMissing
&& $title->isMissing() ? (($title_ppa
= $this->whenPivotLoaded('car_bundle_car_bundle_attribute',
function () {
return (boolean)$this->pivot->custom === true
? $this->pivot->title : $this->title;
})) instanceof PotentiallyMissing
&& $title_ppa->isMissing() ? $this->title : $title_ppa) : $title,
];
}
}
将此代码移动到model模型本身无法确定是否加载了pivot,或者我错了吗?当然可以。当您在资源中使用$this
时,它实际上会将这些调用代理给底层模型对象。好的。所以,如果我通过访问器编辑模型的属性,我可以检查是否加载了透视表?你能给我链接这些文档吗?你只需使用$this->pivot
和$this->pivot->getTable()
来检查pivot是否已加载。