Laravel雄辩地获取当前查询的模型属性

时间:2019-04-01 09:45:08

标签: laravel laravel-5 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();

Product.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');
    }

1 个答案:

答案 0 :(得分:1)

您可以做的是加入:

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中编写联接时,都应该考虑一下您的关系结构,因为可能出了点问题。