无法在advanced :: with()语句中选择列

时间:2014-08-18 11:05:16

标签: php mysql laravel eloquent

我在使用高级query::with语句选择列(MySQL SELECT语句)时遇到问题。

Property::where('public_id', $publicId)->with(['owner' => function ($query) {
    $query->select('email'));
}])->first();

如果我添加select语句,则返回的所有者对象 null ,如果我不添加,则返回完整的User模型添加select('...')语句。

执行的查询是正确的,如果我从phpMyAdmin运行它们,则返回所需的数据:

select * from `properties` where `public_id` = '53f1c59cefe65' limit 1;
select `email` from `users` where `users`.`id` in ('54');

没有选择的数据:

{"id":4,"owner_id":54,"owner":{"id":54,"username":"ckertzmann","email":"ckertzmann@gmail.com","permissions":[],"activated":true,"activated_at":null,"last_login":null,"first_name":"Daisy","last_name":"Haag","created_at":"2014-08-18 09:21:26","updated_at":"2014-08-18 09:21:26"}}

选择数据:

{"id":4,"owner_id":54,"owner":null}

1 个答案:

答案 0 :(得分:1)

您需要选择键,以便Eloquent知道如何将相关模型与其各自的关系父项匹配。

Property::where('public_id', $publicId)->with(['owner' => function ($query) {
    $query->select('email', 'owner_id');
}])->first();