【问题标题】:Laravel Eloquent Get certain columns from nested tables using with()Laravel Eloquent 使用 with() 从嵌套表中获取某些列
【发布时间】:2013-08-26 08:00:26
【问题描述】:

我正在尝试获取具有嵌套继承并针对某些列进行过滤的表。而且找不到好办法。

我有桌子店女巫有很多地点(地点有一个城市)和很多行动

我想使用 Eloquent 一次性获取所有内容并过滤特定列。

这就是我过滤商店表的方式,但不知道如何过滤表位置和操作。

$this->shop->with('locations')->with('actions')->get(array('id','name','recommended','category_id'));

我需要这样的东西:

$this->shop
->with('locations',Location::with('city', City::get(array('id','name')))->get(array('id','name')))
->with('actions', Action::get(array('id','name')))->get(array('id','name')););

【问题讨论】:

    标签: php orm laravel eloquent


    【解决方案1】:

    Laravel Eloquent: How to get only certain columns from joined tables

    最简单的方法是过滤模型中的列(如上面链接的最佳答案所述)。但是,当您想要构建动态查询时,这可能会很不方便。

    理论上你应该可以做到:

    $this->shop->with(array('locations' => function($query) {
                                                $query->select('id', '...etc...');
                                           }
    

    ...不幸的是,它似乎不适用于 select();当我测试它时,我得到了一个空白数组。但是,其他方法确实有效,例如

    $this->shop->with(array('locations' => function($query) {
                                                $query->orderBy('id', 'DESC');
                                           }
    

    使用 Fluent Query Builder 可能会更好。它不像 ORM 那样“性感”或时髦,但我发现它在处理动态查询时更容易使用。

    【讨论】:

    • 好吧,我正在尝试使用查询构建加入表,但它不起作用。 $shops = DB::table('shops') ->join('locations', 'locations.shop_id', '=', 'shops.id') ->join('actions', 'actions.shop_id', '=', 'shops.id') ->select('shops.id','locations.id','actions.id');
    • 如何将多个这些链接在一起?我尝试向数组添加另一个函数,但它失败了。谢谢
    猜你喜欢
    • 1970-01-01
    • 2013-01-21
    • 2013-11-20
    • 1970-01-01
    • 1970-01-01
    • 2015-12-02
    • 2015-12-17
    • 1970-01-01
    相关资源
    最近更新 更多