【问题标题】:In Laravel hasMany relationship How to use with and where?在 Laravel 中有很多关系如何使用 with 和 where?
【发布时间】:2022-07-22 16:11:56
【问题描述】:

在工作模型中:

公共函数 jobApplications()
{
return $this->hasMany(JobApplication::class, 'job_id');
}

在 JobApplication 模型中

公共函数jobs()
{
return $this->belongsTo(Job::class, 'job_id');
}

在 job_applications 迁移中

$table->id();
$table->foreignId("job_id")->constrained("jobs");
$table->foreignId("user_id")->constrained("users");
$table->text('remarks')->nullable();
$table->unsignedInteger('status')->default(1);

我需要获取所有工作及其工作申请,其中 job_applications.status =(用户输入状态)和 job_applications.user_id =authenticated users id。我怎样才能得到它?
下面是我尝试过的语法,它返回未定义的变量状态

$jobs = Job::where('status',1);
$status =$request->状态;

如果($状态){
$jobs = $jobs->whereHas('jobApplications', function($q){
$q->where('status',$status);
$q->where('user_id',Auth()->user()->id);
});
返回 $jobs->get();
任何人都可以提出解决方案吗?

【问题讨论】:

  • 不相关,但如果 JobApplication 有 public function job() 方法,因为它是一个 belongsTo,这不是更有意义。

标签: laravel eloquent relationship where-clause has-many


【解决方案1】:

要在闭包方法中使用外部变量,您需要使用“use”关键字将该变量传递给方法

if($status){
   $jobs = $jobs->whereHas('jobApplications', function($q) use ($status) {
   $q->where('status',$status);
   $q->where('user_id',Auth()->user()->id);
});
return $jobs->get();

【讨论】:

    猜你喜欢
    • 2016-10-12
    • 2020-12-29
    • 1970-01-01
    • 2014-07-10
    • 2015-08-05
    • 2018-07-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多