Fan
Fan

Reputation: 1180

Laravel 5 relationship between to belong

I have a three table vendor banquet project, and the relationship is like following description:
* vendor hasMany banquet and project

class Vendor extends Model
{
   .....
  public function project()
  {
     return $this->hasMany('App\Entities\Project' ,'vendorId' ,'id');
  }

  public function banquet()
  {
     return $this->hasMany('App\Entities\Banquet' ,'vendorId' ,'id');
  }
}

*banquet belongsTo vendor

class Banquet extends Model
{
    ...
    public function vendor()
    {
        return $this->belongsTo('App\Entities\Vendor' ,'vendorId' ,'id');
    }
}

*project belongsTo vendor

class Project extends Model
{
    ...
    public function vendor()
    {
        return $this->belongsTo('App\Entities\Vendor' ,'vendorId' ,'id');
    }
}

And some situation, I just have banquet.id that can find banquet data and at the same time, need to get all of the same vendorId project data within a query.

How can I defined the new relationship between project and banquet? or any idea can find the two kinds data in once query?

Upvotes: 1

Views: 255

Answers (1)

Amit Gupta
Amit Gupta

Reputation: 17658

You can try as:

$banquet = Banquet::where('id', $banquet_id)->with('vendor.project')->first();

then get all of the same vendorId project data as:

$banquet->vendor->project;

it gives the collection of the project.

OR

You can use has-many-through relation to access project from banquet model.

For this create a following function in Banquet.php class

public function project()
{
    return $this->hasManyThrough('App\Entities\Project', 'App\Entities\Banquet');
}

then your query will be like:

$banquet = Banquet::where('id', $banquet_id)->with('project')->first();

$banquet->project;

Upvotes: 3

Related Questions