首页 > 解决方案 > Laravel eloquent 获取当前查询的模型属性

问题描述

我正在尝试为 joindraw 表中的 fortune_code 执行 where 子句,与 product 表中的 lucky_fortune_code 进行比较。我如何访问并进行检查?

Product::where('status', StatusConstant::PT_ENDED_PUBLISHED)
       ->where('lucky_fortune_code', '<>', '')
       ->with(['joindraw' => function ($query){
              $query->where('fortune_code', $this->lucky_fortune_code)
                    ->with('user');}])->desc()->get();

产品.php

class Product extends Model
{
    public function joindraw(){
        return $this->hasMany('App\Models\Joindraw');
    }

Joindraw.php

class Joindraw extends Model
{
    public function product(){
        return $this->belongsTo('App\Models\Product', 'product_id');
    }

标签: laravellaravel-5eloquent

解决方案


你可以做的是加入:

Product::where('status', StatusConstant::PT_ENDED_PUBLISHED)
   ->where('lucky_fortune_code', '!=', '')
   ->join('joindraws', 'joindraws.fortune_code', '=', 'products.lucky_fortune_code')->get();

顺便说一句,您也可以省略关系'product_id'中的第二个参数belongsTo(),因为此列名称已按约定假定。

此外,查询生成器上没有 desc() 方法。改为使用orderBy('lucky_fortune_code', 'desc')

然而,当你必须在 Laravel 中编写连接时,你应该考虑一下你的关系结构,因为可能有问题。


推荐阅读