【发布时间】:2018-10-26 14:05:56
【问题描述】:
我有 3 张桌子:
*document* [id, core_document]
*person* [id, name]
*documentPersonsRole* [document_id, person_id, role] (where role could be accused or victim)
是否可以创建一个快速的方法来从属于-多的关系中返回第一条记录?这是我的代码,来自模型文件:
public function documentPersonsRole()
{
return $this->belongsToMany('App\Models\Person', 'document_person_role')
->withPivot('role')
->withTimestamps();
}
public function accused()
{
return $this->belongsToMany('App\Models\Person', 'document_person_role')
->withPivot('role')
->wherePivot('role', 'accused')
->withTimestamps();
}
public function victim()
{
return $this->belongsToMany('App\Models\Person', 'document_person_role')
->withPivot('role')
->wherePivot('role', 'victim')
->withTimestamps();
}
当我这样称呼时:
App\Models\Document::with('accused')->first()
=> App\Models\Document {#3118
id: 1,
core_document: "Iure aut eum aut ex et. Magni aliquam illo voluptatem non repellat. Maxime occaecati reiciendis veniam quod neque reiciendis dolores. Eaque quis molestiae dolorem. Et rerum veniam animi sit beatae inventore voluptas. Aut ea atque nulla quis quam incidunt iusto voluptas. Aut corrupti voluptas minima unde dicta vero aut veritatis. Voluptas vitae nam mollitia quasi porro id quod ut.",
accused: Illuminate\Database\Eloquent\Collection {#3127
all: [
App\Models\Person {#3139
id: 41,
name: "Jamie",
pivot: Illuminate\Database\Eloquent\Relations\Pivot {#3138
document_id: 1,
person_id: 41,
role: "accused",
created_at: "2018-10-24 03:55:23",
updated_at: "2018-10-24 03:55:23",
},
},
],
},
}
你可以看到 accused 是一个只有一条记录的集合,当我在客户端收到这个时,我必须从数组中提取这条记录,但是我想使用对象。
当我尝试这样的事情时:
public function accused()
{
return $this->belongsToMany('App\Models\Person', 'document_person_role')
->withPivot('role')
->wherePivot('role', 'accused')
->withTimestamps()->first();
}
这是我得到的错误:
带有消息“调用未定义的方法 Illuminate/Database/Query/Builder::addEagerConstraints()”的 BadMethodCallException
如何使用 first() 来检索和反对被告而不是一个记录的数组。
【问题讨论】:
-
不完全确定,但您是否尝试过
belongsToOne而不是belongsToMany? -
@i-- 我很确定
belongsToOne()不存在 -
->belongsTo()?