dongxiangchan0743 2016-09-22 06:23
浏览 43
已采纳

如何在laravel中获得关系

I have three model : Manager ,Vendor, Banquet and the relationship is :

  • manager has one vendor
  • vendor has many banquet

How to get the all manager with all relation in laravel orm?

$manager = Manager::where('active',1)->get();
$vendor = $manager->vendor()->get();// -- dose not work! 
$banquet =  $vendor->banquet()->get();// -- dose not work! 

Manager model:

class Manager extends Model{
     protected $table = 'manager';
     protected $primaryKey = 'id';

     public function vendor(){
     return $this->hasOne('ACME\Entities\Vendor','managerId','id');
   }
}

Here is the model

Vendor model:

class Vendor extends Model{
    protected $table = 'vendor';
    protected $primaryKey = 'id';

    public function manager(){
      return $this->belongsTo('ACME\Entities\Manager_V','id','managerId');
    }

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

Banquet model:

class Banquet extends Model{
    protected $table = 'banquet';
    protected $primaryKey ='id';

    public function vendor()
    {
        return $this->belongsTo('ACME\Entities\Vendor' ,'vendorId' ,'id');
    }
}
  • 写回答

2条回答 默认 最新

  • dpea85385 2016-09-22 06:36
    关注

    Use with method

    $manager =  Manager::with(['vendor','vendor.banquet'])->where('active',1)->get();
    

    You will be able to get data as

    $banquet = $manager->vendor->banquet;
    // $banquet will be array of banquet model objects
    

    Remember hasMany return array, hasOne return Object and belongsTo return Object.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥50 C# 使用DEVMOD设置打印机首选项
  • ¥15 麒麟V10 arm安装gdal
  • ¥15 想用@vueuse 把项目动态改成深色主题,localStorge里面的vueuse-color-scheme一开始就给我改成了dark,不知道什么原因(相关搜索:背景颜色)
  • ¥20 OPENVPN连接问题
  • ¥15 flask实现搜索框访问数据库
  • ¥15 mrk3399刷完安卓11后投屏调试只能显示一个设备
  • ¥100 如何用js写一个游戏云存档
  • ¥15 ansys fluent计算闪退
  • ¥15 有关wireshark抓包的问题
  • ¥15 需要写计算过程,不要写代码,求解答,数据都在图上