我有一个分配模型,它包含一个MorphOne到一个MessageThread模型。
class Assignment extends Model
{
/**
* @return MorphOne<AppMessageThread>
*/
public function messageThread(): MorphOne
{
return $this->morphOne("AppMessageThread", "messageable");
}
}
class MessageThread extends Model
{
/**
* The attributes that are mass assignable.
*
* @var string[]
*/
protected $fillable = [
"messageable_id",
"messageable_type",
"status",
"account_id",
"public",
"title",
"direct",
];
public function users(): BelongsToMany
{
return $this->belongsToMany(
"AppUser",
"message_thread_user",
)->withPivot("read");
}
public function messages(): HasMany
{
return $this->hasMany("AppMessage");
}
public function messageable(): MorphTo
{
return $this->morphTo();
}
}
下面的代码为每个赋值加载MessageThread关系
$assignments = AppAssignment::where("account_id", $account_id)
->with("messageThread")
->withCount(["logs", "messages"])
->paginate(30);
List of objects: [
{
"id": 378065,
...,
"message_thread": {
"id": 159809,
...,
"messageable_type": "App\Assignment",
"created_at": "2022-08-26T20:36:38.000000Z",
"updated_at": "2022-08-26T20:36:38.000000Z",
}
}
]
然而,我只想加载消息线程的id。我不需要加载整个模型。当我搜索如何做到这一点时,看起来我需要用query来替换:
$assignments = AppAssignment::where("account_id", $account_id)
->with("messageThread:id")
->withCount(["logs", "messages"])
->paginate(30);
我还尝试过做一个查询选择器,据我所知,这是做messageThread:id
的更详细的方法。
$assignments = AppAssignment::where("account_id", $account_id)
->with(["messageThread" => function ($query) {
$query->select("id");
}])->withCount(["logs", "messages"])
->paginate(30);
问题是,我最终与JSON响应中的message_thread的空值:
[
{
"id": 378065,
...,
"message_thread": null
},
]
我知道问题不在于MessageThread不存在,因为如果我不指定列,它加载完全没问题。
我试着搜索这类错误,但是一无所获。
messageable_id
需要包含在select中,以便匹配Assignment和MessageThread模型
$assignments = AppAssignment::where("account_id", $account_id)
->with(["messageThread" => function ($query) {
$query->select("message_thread.id, message_thread.messageable_id");
}])
->withCount(["logs", "messages"])
->paginate(30);
演职表:https://laracasts.com/discuss/channels/eloquent/select-columns-on-relationship-tables?page=1&replyId=755706