jeudi 24 janvier 2019

Laravel 5.7 select only relationship data without loop through other relationship

I have 3 tables 1) product 2) comment 3) user

one product can have many comments and one comment belongs to one user only. here is a relationship which I defined for all 3 models.

1) Product Model

class product{
     public function comments(){
           return $this->hasMany(Comments::class,'product_id');
     }
}

2) Comments Model

class comments{

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

     public function user(){
           return $this->hasOne(User::class,'id','user_id');
     }
}

3) User Model

class User{
     public function comment(){
           return $this->belongsTo(Comments::class);
     }
}

I want to get all users who commented on the product. (I know I can do by with() and loop through product and comment but I don't want to loop through all comments, I want all users in an answer without comment data.)


In short from product id I want all users data who commented on that product (without loop through all comment)




via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire