1

I need to query and check if the relationship column is the same in my main table column.

example codes:

not working

User::with('product', => function($q) {
                $q->whereRaw('users.company_id',' product.company_id');
            })->get();

not working

User::with('product', => function($q) {
                $q->whereRaw('users.company_id = product.company_id');
            })->get();

not working

User::with('product')->whereColumn('users.company_id', 'product.company_id')->get();

but it's not working.. any idea how to do it?

My Models

User Model

public function product()
{
    return $this->belongsTo(Product::class, 'product_id');
}

Product Model

public function users()
{
    return $this->hasMany(User::class, 'product_id');
}
3
  • Could you show us all the models (User, product and company) and show us the file/function you are trying to edit it in. If the answer doesn't work Commented Jun 23, 2020 at 0:59
  • it's just an example models. but the codes the same in my codes. Commented Jun 23, 2020 at 1:05
  • What about your company model? If you don't have 1 I would suggest you make one makes the relation stuff easier. Commented Jun 23, 2020 at 11:20

2 Answers 2

2

Please try again:

User->with(['product' => function ($query) {
    $query->join('users', 'users.company_id', '=', 'product.company_id');
}])->get();
Sign up to request clarification or add additional context in comments.

3 Comments

as much as possible I don't want to use join in this situation.
I tried it, and the result was changed or wrong, the query remove users record that doesnt have product.
the query is correct, but if you can see my Product Model, product model has many users, so if I use join inside product query the query response become longer. in my side from 1290ms change to 3.0s. anyway I upvote your answer :)
0

Try to use DB:raw() then show the table info? like this

Comments

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.