dekoy_
dekoy_

Reputation: 21

How to query Laravel 5.1 Eloquent

I have a projects table and an items table. Rents table is the middle eloquent. It shows what project rented or used what item. How can I retrieve a project and all items used without necessarily involving rents in the result.

Schema:

enter image description here

Projects

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

Items

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

Rents

 public function project()
   {
   return $this->belongsTo('Project');
   }
   public function item()
   {
        return $this->belongsTo('App\Item');
   }

Thank you in anticipation.

Upvotes: 1

Views: 182

Answers (1)

Mina Abadir
Mina Abadir

Reputation: 2981

In order to achieve what you are looking for, you need to use a different relation hasManyThrough, simply adjust your Project models as below:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Project extends Model
{
    public function items()
    {
      return $this->hasManyThrough('App\Item','App\Rent');
    }
}

Upvotes: 2

Related Questions