【问题标题】:Data is not received in relation to whereHas Laravel没有收到与 whereHas Laravel 相关的数据
【发布时间】:2021-09-23 08:58:41
【问题描述】:

我一直在尝试查询 whereHas 并且无法检索数据。 看看我是怎么尝试的。 在我将另一个如何获取数据的位置放在另一个位置之后,我创建了一个 whereHas where 我有一个查询功能。 请记住 where 指的是偏差而不是 discount_codes

public function showPopupData(Request $request)
    {
        $id = Auth::user()->company_id;

        $data = Popup::getPopupByCompanyId($id);

        $biases = Bias::whereHas('discount_codes', function ($query) {
            $query->where('discount_code.id', '=', 'bias.discount_code_id');
        })->get();
       

        return response()->json(['data' => $data, 
                        'biases' => $biases
                        ]);
    }

应该保持,在下一个关系中,我也收到了与我有关系的数据。

 $biases = Bias::with('discount_codes')->where('company_id', '=', $id)->get();

型号

public function discount_codes()
    {
        return $this->belongsTo('App\Models\DiscountCode', 'discount_code_id', 'id');
    }
 public function biases() 
    {
        return $this->hasMany('App\Models\Bias', 'id', 'discount_code_id');
    }

表格

Discount code
$table->increments('id');
            $table->string('discount_code')->nullable();
Bias
 $table->integer('discount_code_id')->nullable()->unsigned();
 $table->foreign('discount_code_id')->references('id')->on('discount_codes')->onDelete('cascade');

你认为我在这里做错了什么?

【问题讨论】:

    标签: laravel eloquent


    【解决方案1】:

    首先,您的代码是多余的。

    Bias::whereHas('discount_codes', function ($query) {
        $query->where('discount_code.id', '=', 'bias.discount_code_id');
    })->get();
    

    您已经通过调用关系使用主键和外键连接了两个表。您不必再次检查 id。

    如此简单的with 工作正常

    $biases = Bias::with('discount_codes')->where('company_id', $id)->get();
    

    现在,如果您只想要那些具有 discount_codes 的记录,您可以检查与 has 的关系是否存在

    $biases = Bias::has('discount_codes')->with('discount_codes')->where('company_id', $id)->get();
    

    现在在你的偏见关系中,你把钥匙放在了错误的地方。应该是

    public function biases() 
    {
        return $this->hasMany('App\Models\Bias', 'discount_code_id', 'id');
    }
    

    最后你弄乱了命名约定。您应该考虑遵循标准命名约定。

    【讨论】:

      【解决方案2】:

      这里不需要关系 "whereHas" 条件,因为 "has" 函数的作用与您在此处尝试实现的相同,只需使用 "has" 运算符即可。

      $biases = Bias::has('discount_codes')->get();

      【讨论】:

        【解决方案3】:

        我觉得你可以用has()

        $biases = Bias::with('discount_codes')->has('discount_codes')->get(); 
        

        【讨论】:

          猜你喜欢
          • 2020-12-23
          • 1970-01-01
          • 2022-08-19
          • 2014-01-11
          • 1970-01-01
          • 2018-10-18
          • 2021-05-25
          • 2018-09-18
          • 2023-03-09
          相关资源
          最近更新 更多