【问题标题】:Fetch Specific Columns in table with specific column in relationship table in Laravel Eloquent在 Laravel Eloquent 中使用关系表中的特定列获取表中的特定列
【发布时间】:2021-12-30 00:10:23
【问题描述】:

这里我有两个模型。用户和公司。

内部用户模型:

public function company()
{
    return $this->hasOne(Company::class);
}

公司内部模型:

public function user()
{
    return $this->belongsTo(User::class);
}

当我使用以下查询获取用户时:

User::query()
        ->with(array('company' => function($company) {
            return $company->select('id', 'company_name');
        }))->get()->map->only([
            'id', 'email', 'has_employees', 'created', 'status', 'last_login_ago_day', 'company_name'
        ]);

此代码仅返回用户模型的特定列。我还想返回公司模型的特定列。我该怎么做?

【问题讨论】:

  • only 方法只返回指定的键,因为你没有指定company_name,所以它不会返回它
  • 我在退货单中添加了 company_name,但所有公司名称都为空值
  • 您需要将company 添加到您的 only() 方法中。它将是一个包含所有公司字段的嵌套对象
  • 是的,如果您还在公司函数中添加外键 id 是正确的

标签: laravel eloquent orm laravel-query-builder


【解决方案1】:

需要在公司关闭函数中添加外键ID,在本例中为user_id

User::query()->role('admin')->with(['company' => function($company) {
        $company->select('user_id', 'company_name');
    }])->get()
        ->map->only([
            'id', 'email', 'has_employees', 'created', 'status', 'last_login_ago_day', 'company'
        ]);

【讨论】:

    猜你喜欢
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2020-07-12
    • 1970-01-01
    • 2013-11-20
    • 2017-02-22
    • 1970-01-01
    相关资源
    最近更新 更多