Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 如何获得具有morphotomy关系的第一个对象?_Php_Laravel - Fatal编程技术网

Php 如何获得具有morphotomy关系的第一个对象?

Php 如何获得具有morphotomy关系的第一个对象?,php,laravel,Php,Laravel,我的项目表上有一个多态关系 public function categories(): MorphToMany { return $this->morphToMany(Category::class, 'categorizable', 'categorizables', 'categorizable_id', 'category_id') ->withTimestamps(); } 它起作用了。我得到了预期的对象列表。只是,我数据库中的某些模型始终只有一个类

我的项目表上有一个多态关系

public function categories(): MorphToMany
{
    return $this->morphToMany(Category::class, 'categorizable', 'categorizables', 'categorizable_id', 'category_id')
        ->withTimestamps();
}
它起作用了。我得到了预期的对象列表。只是,我数据库中的某些模型始终只有一个类别

我想避免得到一份物品清单。我想要的对象直接

我试过了,但没用:

public function category()
{
    return $this->morphToMany(Category::class, 'categorizable', 'categorizables', 'categorizable_id', 'category_id')->first;
}
调用未定义的方法App\Models\Category::addagerConstraints()

我有这样一个结果:

{
  'id': 1,
  'name': 'My name',
  'categories': [
    {my object category}
   ]
}
我想:

{
  'id': 1,
  'name': 'My name',
  'category': 
    {my object category}
}

我该怎么做?这是一种多对多多态关系。

morphotomy类似于HasMany(),它总是返回一个数组

您可以使用Eloquent
访问器
获取类别并操作数据

protected $appends = ['category_data'];

public function getCategoryDataAttribute()
{       
    return $this->categories->first();
}