【问题标题】:Laravel Eloquent how to select relation field as certain fields of main objectLaravel Eloquent 如何选择关系字段作为主要对象的某些字段
【发布时间】:2016-02-11 04:38:23
【问题描述】:
$select = Model::with(['relation' => function($query) {
    $query->select('id', 'somefield');
}])->get();

使用此代码时,我得到了我的 Model 对象,其中包含 relation 字段,其中包含 somefield

{
    ... some Model fields
    ...
    relation => {
        id => someid
        somefield => somevalue
    }
}

但是如果我需要 somefield 代替 Model 的字段呢?

{
    ... some Model fields
    ...

    somefield => somevalue
}

编辑:换句话说,我想使用 Eloquent 获得与以下查询相同的结果

\DB::table('table1')
    ->select('table1.field1', 'table2.field2 as otherfield', 
    ->leftJoin('table2', 'table2.id', '=', 'table1.parent_id')->get();

【问题讨论】:

  • 你能做model.somefield吗?
  • @Anoxy 我希望能够调用 Model->somefield,而不是 Model->relation->somefield
  • 我将只使用 laravel pluck 函数然后示例: $shopAddresses = Shop::where('name', 'Starbucks')->pluck('address');

标签: php laravel select laravel-4 eloquent


【解决方案1】:

像这样使用 Laravel plcuk 方法:

$shopAddresses = Shop::where('name', 'Starbucks')->pluck('address');

【讨论】:

  • 你应该可以做到 ->pluck('address, 'joinfield.address)
猜你喜欢
  • 2019-03-04
  • 2016-04-29
  • 2020-09-27
  • 1970-01-01
  • 2020-09-23
  • 2016-08-17
  • 1970-01-01
  • 2022-07-16
  • 2015-10-10
相关资源
最近更新 更多