Laravel Eloquent的select函数导致关联数据为空

4
以下是我的查询。
$user = User::select(['uuid','name','about'])->with(['education','work'])->first();

这将返回与关系"education"和"work"相关的空数据, 但是,如果我从查询中删除"select"函数,则会获得与关系相关的数据,并且它还返回用户表的所有列,而我不需要。

如何解决这个问题?

2个回答

12

问题在于关系(with(...))会执行一个额外的查询来获取相关的结果。假设你有一个一对多的关系,其中users有许多worksUser::with('work')->find(1)将执行这两个查询:

select user where id = 1select works where user_id = 1

因此,在能够执行第二个查询(获取关系数据)之前,你需要在你的选择语句中包括id(或者你正在引用的任何列)。

修复:

$user = User::select(['uuid','name','about', 'id'])->with(['education','work'])->first();

不同形式的相同原则适用于所有关系。例如,在hasMany的反向关系belongsTo中,您需要选择外键(例如user_id)。


0

可能存在的一个问题是,如果您使用select()与with()一起来急切加载关系,则with()方法可能无法按预期工作。这是因为当您使用select()时,Laravel仅检索指定的列,并且不检索任何关联数据。因此,当您尝试使用with()急切加载关系时,Laravel可能没有所需的数据。

wrong::

 'products' => $this->product
                        ->with('files', 'categories', 'sub_categories')
                        ->select('title', 'slug', 'sku')**
                        ->orderBy('id', 'DESC')->paginate(20)

正确 ::

 'products' => $this->product
                ->with('files', 'categories', 'sub_categories')
                ->select('id','title', 'slug', 'sku')
                ->orderBy('id', 'DESC')->paginate(20)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接