1myb
1myb

Reputation: 3596

Laravel eloquent get model property of current query

I'm trying to do where clause for fortune_code inside joindraw table, comparing with the lucky_fortune_code from product table. How can i access and do the check?

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

Upvotes: 0

Views: 534

Answers (1)

Lupinity Labs
Lupinity Labs

Reputation: 2464

What you can do is a join:

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

By the way, you can also omit the second 'product_id' parameter in the belongsTo() relation, as this column name is already assumed by convention.

Also, there is no desc() method on the query builder. Use orderBy('lucky_fortune_code', 'desc') instead.

However, whenever you have to write joins in Laravel, you should think about your relationship structure, because there's probably something wrong.

Upvotes: 1

Related Questions