【问题标题】:Laravel - Get column names when eager loading from the modelLaravel - 从模型中急切加载时获取列名
【发布时间】:2019-09-19 23:35:31
【问题描述】:

在模型中指定预加载时如何获取列名?

这是我正在尝试做的一个示例,但它不起作用。我似乎无法从渠道模型中选择任何列。

$query = Transaction::select('id', 'processing_time', 'uniqueId', 'paymentType', 'status', 'channel:uuid');

return $query->take(5)->get();

但是,如果我这样做,我会从交易和渠道中获得一切,因此关系就在那里并且有效。

$query = Transaction::limit(5);

return $query->get();

交易模型

protected $with = ['channel'];

public function channel() {
    return $this->belongsTo(Channel::class, 'entityId', 'uuid');
}

渠道模式

public function transactions() {
    return $this->hasMany('App\Transaction', 'entityId', 'uuid');
}

【问题讨论】:

  • 在 select 语句中添加 entityId 列,然后它将检索通道关系的数据。
  • 试过了,没用,伙计

标签: laravel eloquent


【解决方案1】:

根据有关急切加载的文档:

When using this feature, you should always include the id column and any relevant foreign key columns

试试:

$query = Transaction::select('id', etc.., 'channel:id,uuid');

或者

$query = Transaction::select('id', etc..)->with('channel:id,uuid');

【讨论】:

    【解决方案2】:
        $query = Transaction::with(['channels' => function($query){
                 $query->select('you', 'colums')
        });
    

    您可以像这样在您的关系中使用 Select。

    【讨论】:

    • 但是如果模型中指定了“with”,是否需要在控制器中再次指定才能使这个工作?似乎有点多余。
    【解决方案3】:

    在通道模型中添加选择为

    public function channel() {
        return $this->belongsTo(Channel::class, 'entityId', 'uuid')->select(array('columns name you want to get'));
    }
    

    【讨论】:

    • 然后我将如何在查询中指定列?频道:uuid 仍在带回未知列。
    猜你喜欢
    • 2021-11-29
    • 2013-03-27
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 2013-06-10
    • 2013-05-16
    • 2019-05-19
    • 2015-06-19
    相关资源
    最近更新 更多