【问题标题】:Inner join single column using Eloquent使用 Eloquent 内连接单列
【发布时间】:2014-06-15 06:19:23
【问题描述】:

我正在尝试获取内部连接模型的单列

$items = Item::with('brand')->get();

这也给了我整个brand 对象,但我只想要brand.brand_name

$items = Item::with('brand.brand_name')->get();

对我没用。

我怎样才能做到这一点?

【问题讨论】:

  • 你总是只想要brand_name ..还是只在这种情况下希望对象只包含“brand_name”?
  • 只是为了完整起见:急切加载(使用with)不使用连接,而是使用WHERE IN 查询。后者确实可以很好地扩展。

标签: php orm laravel laravel-4 eloquent


【解决方案1】:

这将获得相关模型(另一个查询),其中仅包含您想要的列(一个 id,见下文):

$items = Item::with(['brand' => function ($q) {
   $q->select('id','brand_name'); // id is required always to match relations
                                  // it it was hasMany/hasOne also parent_id would be required
}])->get();
// return collection of Item models and related Brand models. 
// You can call $item->brand->brand_name on each model

另一方面,你可以简单地加入你需要的东西:

$items = Item::join('brands', 'brands.id', '=', 'items.brand_id')
   ->get(['items.*','brands.brand_name']);
// returns collection of Item models, each having $item->brand_name property added.

我猜Item 属于Brand,表名是itemsbrands。如果不是,请相应地编辑这些值。

【讨论】:

    【解决方案2】:

    试试这个:

      $items = Item::with(array('brand'=>function($query){
              $query->select('name');
      }))->get();
    

    【讨论】:

      猜你喜欢
      • 2019-10-24
      • 2014-03-27
      • 1970-01-01
      • 2018-11-06
      • 1970-01-01
      • 2015-06-13
      • 2020-04-26
      • 1970-01-01
      • 2015-03-22
      相关资源
      最近更新 更多