Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

prasatharumugam's avatar

Eloquent relation gives wrong result

Hi I have three tables

user
----------------------
id   name  
user_products
-------------------
id  user_id   product_id
Products
--------------------------
id    product_name

Relations are done like following

Class User{

    public function UserProducts(){
         
            return $this->hasMany('UserProducts', 'id', 'user_id');      
        
    }

}
Class UserProducts{

    public function Products(){
        
        return $this->belongsTo('Products', 'product_id', 'id');
    }
}

Now my query is this

    Users::with(array(
        'UserProducts' => function ($query) use($productId) {
            $query->where("product_id","=", $productId);
            $query->with('Products');
            
        }))->get();

The problem is the where query on the relation works well, but returns the records which is not = $productId Mentioned in the where clause.

Has anyone gone through this situation before. Please help

0 likes
5 replies
katifrantz's avatar

It looks like you are trying to achieve a many-to-many relationship ... Am I right ? You database tables are correct for a many-to-many relationship , but your models are wrong . And please tell us the query you are trying to achieve in plain english . Then we will offer more help

prasatharumugam's avatar

Ok, lets say I have product ID:1

I want all the users who preferred for product ID:1 and the corresponding product details. I meant preference as user_products

M4rk3tt0's avatar

Name the tables like this to follow the conventions.

users
----------------------
id   name  
product_user
-------------------
id  user_id   product_id
products
--------------------------
id    product_name

The models

class User extends Authenticatable
....
{
        public function products()
        {
            return $this->belongsToMany('App\Product');
        }
    ...
}
class Product extends Model
....
{
        public function users()
        {
            return $this->belongsToMany('App\User');
        }
    ...
}

And then you use it like this:

$product = Product::find($id);
$users = $product->users();
willvincent's avatar

And then you use it like this:

$product = Product::find($id);
$users = $product->users();

or like this.. :)

$product = Product::find($id)->with('users');

Please or to participate in this conversation.