0

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');
    }
9
  • where do you get this "$this->lucky_fortune_code" ? Commented Apr 1, 2019 at 9:46
  • @GauravGupta I'm unable to get it. Was thought able to do it like in the model Commented Apr 1, 2019 at 9:47
  • try with product.lucky_fortune_code or just lucky_fortune_code Commented Apr 1, 2019 at 9:48
  • tried $query->where('fortune_code', 'lucky_fortune_code') and $query->where('fortune_code', 'product.lucky_fortune_code') returns nothing Commented Apr 1, 2019 at 9:52
  • show your model and relationship between models Commented Apr 1, 2019 at 9:56

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I want to access the lucky_fortune_code in table Product itself. I don't have the variable predefined.
How can i join the joindraws table with user table?
Thanks for your reminder! I've written the scope in model file for easy maintainance. The system will need to change the ordering based on situation.
I got it! Simply ->with('user') will do. Thanks!!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.