【问题标题】:Laravel: Getting extra column (from other model) in eloquent queryLaravel:在雄辩的查询中获取额外的列(来自其他模型)
【发布时间】:2019-06-23 15:43:54
【问题描述】:

-- 我期待什么--

我正在根据另一个选择的选择填写表单选择。

第一个选择是:

{{Form::select('country',$countries,$player->city->country->id,['class' => 'form-control','id' => 'selectCountry'])}}

第二个选择应填写与该国家/地区相关联的城市。

-- 我的控制器试图接收必要的信息--

return Country::find($request->get('country'))->cities->where('player_id','!=',null);

这一切都很好。现在问题来了,我的 JSON 对象(模型 Country)有一个 player_id,但我希望结果还包括他在 App\Player 模型中找到的“player_name”列。

有人知道如何构建 Eloquent 查询吗?还是只能通过 DB:: 查询来完成,如果可以,我该如何构建这个查询?

提前感谢您的帮助!

【问题讨论】:

    标签: php laravel eloquent


    【解决方案1】:

    如果 Country 表上有一个 player_id 列,那么 Country 模型上应该有一个 player() 关系。

    所以你可以这样做:

    return Country::find($request->get('country'))->cities->where('player_id','!=',null)->with('player');
    

    然后$country->player->player_name;

    【讨论】:

    • 我收到此错误消息:Method Illuminate\Database\Eloquent\Collection::with 不存在。
    • 好的,您的代码几乎是正确的,但它需要在 with 之前的 each:
    猜你喜欢
    • 2016-04-19
    • 2017-05-24
    • 2019-06-27
    • 2019-07-16
    • 2018-01-26
    • 2021-07-23
    • 1970-01-01
    • 2021-11-09
    相关资源
    最近更新 更多