【问题标题】:Laravel 6.2: Laravel "with" not working with conditionLaravel 6.2:Laravel“与”不符合条件
【发布时间】:2020-03-19 07:52:04
【问题描述】:

我正在使用 Laravel 6.2 开发一个项目。我有两个模型。

  1. 工作
  2. 公司

我想要做的是获得所有职位匹配something 并且company city 等于something 的职位。问题是,它正在与公司合作,但如果我指定错误的company city,它仍然会得到记录。简而言之,with 内的条件不起作用。到目前为止我做了什么:

模型 > Job.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Job extends Model
{
    // user
    public function user()
    {
        return $this->belongsTo('App\User');
    }

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

模型 > Company.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Company extends Model
{
    // user
    public function user()
    {
        return $this->belongsTo('App\User');
    }

    // job
    public function job()
    {
        return $this->hasMany('App\Job');
    }
}

JobController > 搜索

public function search(Request $request)
{
     $jobs = Job::where('title', 'like', '%' . $request->q . '%')
               ->with(['company' => function($q) use ($request) {
                    $q->where('city', $request->city);
                }])
                ->get();


     return view('jobs.view')->withJobs($jobs);
}

【问题讨论】:

  • 你好,在你的情况下你必须`->get();`

标签: php laravel eloquent laravel-6.2


【解决方案1】:

试试下面的功能:

public function search(Request $request)
{
     $jobs = Job::where('title', 'like', '%' . $request->q . '%')
               ->with(['company'])
               ->whereHas('company',function($q) use ($request) {
                    $q->where('city', $request->city);
                })
                ->get();


     return view('jobs.view')->withJobs($jobs);
}

【讨论】:

  • 即使我删除了-&gt;with(['company']) 部分,您的答案代码仍然有效。为什么?
  • -&gt;with(['company']) 只会选择公司关系,whereHas 将过滤公司所在的城市。如果您想要公司详细信息,则可以使用“with(['company'])”,如果不想要,则可以删除该部分。
  • 如果我删除该部分,公司详细信息仍然可用
【解决方案2】:

在你的控制器中!

public function search(Request $request)
{
   $jobs = Job::where('title', 'like', '%' . $request->q . '%')
           ->with(['company' => function($q) use ($request) {
                $q->where('city', $request->city)->get();
            }])
            ->get();


   return view('jobs.view')->withJobs($jobs);
}

【讨论】:

    猜你喜欢
    • 2019-06-22
    • 2021-03-16
    • 2018-05-24
    • 1970-01-01
    • 1970-01-01
    • 2021-12-18
    • 2021-10-13
    • 2019-07-11
    • 1970-01-01
    相关资源
    最近更新 更多