【问题标题】:Laravel with relation returning inaccurate resultLaravel 的关系返回不准确的结果
【发布时间】:2019-11-22 20:33:44
【问题描述】:

我正在尝试进行查询以获取所有采访并在公司表中获取公司名称。我只想返回公司表中的名称列。

我运行了一个查询日志,发现我的关系返回了一个奇怪的查询。

Laravel 版本 6.5.2

我原本拥有的东西

$interviews = Interview::select('title', 'slug', 'subtitle', 'posted_date')
                                    ->orderBy('created_at', 'DESC')
                                    ->with(['company' => function($query) {
                                        $query->select('id','name');
                                    }])
                                    ->get();

我现在使用的只是为了测试关系是否有效:

\DB::enableQueryLog();

$interviews = Interview::select('title', 'slug', 'subtitle', 'posted_date')
                                    ->orderBy('created_at', 'DESC')
                                    ->with('company')
                                    ->get();
dd(\DB::getQueryLog());

公司模式:

public function interview() {
        return $this->hasOne('App\Interview', 'company_id', 'id');
    }

面试模型:

public function company() {
        return $this->belongsTo('App\Company', 'id', 'company_id');
    }

结果:

select `title`, `slug`, `subtitle`, `posted_date` from `interviews` where `interviews`.`deleted_at` is null order by `created_at` desc

select * from `companies` where 0 = 1 and `companies`.`deleted_at` is null

我试图弄清楚为什么它返回 where 0 = 1 而不是实际模型。

另外,有没有办法只返回上面我这样的一个字段?

【问题讨论】:

标签: php laravel laravel-5 eloquent


【解决方案1】:

找到答案。您必须在原始查询中指定 idcompany_id 才能使其正常工作。

$interviews = Interview::select('id', 'title', 'company_id', 'slug', 'subtitle', 'posted_date')
  ->orderBy('created_at', 'DESC')
  ->with(['company:id,name'])
  ->get();

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-16
    • 1970-01-01
    • 1970-01-01
    • 2013-01-15
    • 2021-09-19
    • 2023-03-25
    相关资源
    最近更新 更多