简体   繁体   English

Laravel 5之间的关系属于

[英]Laravel 5 relationship between to belong

I have a three table vendor banquet project , and the relationship is like following description: 我有一个三桌vendor banquet project ,关系如下:
* vendor hasMany banquet and project * vendor banquetproject

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 * banquet属于vendor

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

* project belongsTo vendor * project属于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. 在某些情况下,我只有banquet.id可以找到banquet数据,同时需要在查询中获得所有相同的vendorId project数据。

How can I defined the new relationship between project and banquet ? 我怎样才能定义projectbanquet之间的新关系? or any idea can find the two kinds data in once query? 或任何想法可以在一次查询中找到两种数据?

You can try as: 您可以尝试:

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

then get all of the same vendorId project data as: 然后得到所有相同的vendorId project数据:

$banquet->vendor->project;

it gives the collection of the project. 它给出了项目的集合。

OR 要么

You can use has-many-through relation to access project from banquet model. 您可以使用has-many-through关系从banquet模型访问project

For this create a following function in Banquet.php class 为此,在Banquet.php类中创建以下函数

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;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM