dongyue6199 2014-10-28 16:00
浏览 36
已采纳

Laravel限制(不是全球)

I have the following query I want to execute with Eloquent.

$restaurant = Restaurant::with([
    'user' => function($query)
    {
        $query->select(['username']); // This doesn't work
        $query->whereStatus('confirmed');
    }
])->find($id);

I want to fetch a Restaurant and it's corresponding User (they are related) but from the User I don't wan't all the information. Only the username in this case.

I could add a property $hidden to the User model, but then they would be hidden for every query (in array / json form). But I only want to limit it a bit more for this query.

If I add the select (with or without wrapping it in an array) I get the following result:

{
    'id': 1,
    'user': null
}

Yet if I remove that select I get the full User:

{
    'id': 1,
    'user': { .. json user data }
}

The User does exist and the username is not empty. How can I go about this?

Here the actual output can be found.

Edit: When I change the value in the select to something that does not exist in the database I see an error, and from that I deduct that the Query is correct, but I just don't get any output. (Query I get when using an invalid column 'test').

select `test` from `users` where `users`.`deleted_at` is null and `users`.`userable_id` in (1) and `users`.`userable_type` = Restaurant and `status` = confirmed)
  • 写回答

1条回答 默认 最新

  • dougangxin5695 2014-10-28 16:23
    关注

    Try this way:

    $restaurant = Restaurant::with([
        'user' => function($query)
        {
            $query->whereStatus('confirmed')->lists('username');
        }
    ])->find($id);
    

    EDIT

    It seems that both methods will work but you need to fulfil one condition - you need to include foreign_key column in the lists/select. I don't know what is your relation but for example assuming you have in users table restaurant_id column you would need to use the following code:

    $restaurant = Restaurant::with([
        'user' => function($query)
        {
            $query->select(['username', 'restaurant_id'])->whereStatus('confirmed');
        }
    ])->find($id);
    

    or

    $restaurant = Restaurant::with([
        'user' => function($query)
        {
            $query->whereStatus('confirmed')->lists('username','restaurant_id');
        }
    ])->find($id);
    

    I don't know if it is possible for n:n relationship. You should also consider that this might be a bit dangerous (some problems may occur) so you should play with it only if you have strong reason just to grab selected columns.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 任务A:大数据平台搭建(容器环境)怎么做呢?
  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计