tehseen
2 weeks ago
311
14
General

author and product relationship query issue

Posted 2 weeks ago by tehseen

I want to get all author with their product at least 5 but the query is not working

$users = User::with(['products' => function ($query) {
            $query->limit(6);
        }])->get();

the above query will return something like below

Collection {#382 ▼
  #items: array:5 [▼
    0 => User {#412 ▼
      #fillable: array:3 [▶]
      +sortable: array:3 [▶]
      #hidden: array:2 [▶]
      #connection: "mysql"
      #table: null
      #primaryKey: "id"
      #keyType: "int"
      +incrementing: true
      #with: []
      #withCount: []
      #perPage: 15
      +exists: true
      +wasRecentlyCreated: false
      #attributes: array:15 [▶]
      #original: array:15 [▶]
      #changes: []
      #casts: []
      #dates: []
      #dateFormat: null
      #appends: []
      #dispatchesEvents: []
      #observables: []
      #relations: array:1 [▶]
      #touches: []
      +timestamps: true
      #visible: []
      #guarded: array:1 [▶]
      #rememberTokenName: "remember_token"
      -roleClass: null
      -permissionClass: null
    }
    1 => User {#413 ▶}
    2 => User {#414 ▶}
    3 => User {#415 ▶}
    4 => User {#416 ▶}
  ]
}

The first user only have product not all, but in my database both first and second author have product

Its relationship between user/author and products one to many

in my user modal

public function products() {
        return $this->hasMany('App\Product');
    }

in my product modal

 public function user() {
        return $this->belongsTo('App\User', 'user_id');
    }

and in database we have user_id in product table.

Please help

Please sign in or create an account to participate in this conversation.