我有以下User::class
条:
class User extends Authenticatable
{
/* ........ */
protected $with = ['subscription', 'photo'];
public function subscription(): HasOne
{
return $this->hasOne(Subscriptions::class, 'id', 'subscription_id');
}
public function photo(): HasOne
{
return $this->hasOne(Files::class, 'id', 'photo_file_id');
}
}
通过使用$with
,在查询User::class
时总是加载关系subscription
和photo
.
然而,有时我想避免这种关系.The documentation表示:
如果要覆盖$WITH属性中的所有项 对于单个查询,可以使用with Only方法:
因此,考虑到这一点,我执行了以下查询:
$notifications = \App\Models\Notifications::withOnly('fromuser')
->where('to_user_id', auth()->user()->id)
->limit(15)
->orderBy('id', 'DESC')
->get();
然而,Laravel Debug Bar显示同时加载了subscription
和photo
个关系.另外,如果我输出$notifications->toArray()
,那么关系也会显示出来.
这Notifications::class
个字相当直白:
class Notifications extends Model
{
/* ..... */
public function fromuser(): HasOne
{
return $this->hasOne(User::class, 'id', 'from_user_id');
}
public function touser(): HasOne
{
return $this->hasOne(User::class, 'id', 'to_user_id');
}
}
我错过了什么吗?
Edit:我知道我可以做到:
\App\Models\Notifications::with(['fromuser' => function($query)
{
$query->without(['subscription', 'photo']);
}])
但我希望避免这种情况,因为:
- 我打
User::class
是几百个地方 - 我以后可能会添加更多的关系
如果不可能只做->withOnly
,我可能会忘记使用$with
属性.