【问题标题】:Laravel 3 Eloquent ORM for 3 level relation & filterLaravel 3 Eloquent ORM 用于 3 级关系和过滤器
【发布时间】:2014-12-27 19:07:19
【问题描述】:

我有 3 个模型:

模型 A

class A extends \Eloquent {
    ...
    public function Bs() {
        return $this->belongsTo('B','B_id','id');
    }
    public function Xs() {
        return $this->belongsTo('X','X_id','id');
    }
    public function Ys() {
        return $this->belongsTo('Y','Y_id','id');
    }
    ...
}

模型 B

    class B extends \Eloquent {
        ...
    public function As()
    {
            return $this->hasMany('A');
    }
        public function Cs()
        {
            return $this->hasMany('C');
    }
        ...
   }

模型 C

 class c extends \Eloquent {
        ...
    public function Bs()
    {
            return $this->belongsTo('B','B_id','id');
    }
    public function Zs()
    {
            return $this->belongsTo('Z','Z_id','id');
    }
        ...
   }

我需要 A 的所有数据,并在 X、Y 和 Z 上使用过滤器。然后我像这样将 hasManyThrough() 添加到 C

模型 C

    class c extends \Eloquent {
        ...
    public function Bs()
    {
            return $this->belongsTo('B','B_id','id');
    }
    public function Zs()
    {
            return $this->belongsTo('Z','Z_id','id');
    }
    public function As()
    {
            return $this->hasManyThrough('A','B','id','B_id');
    }
        ...
   }

但是当我使用这样的控制器获取数据时:

 public function index()
 {

 $output=C::where('Z_id','=',Input::get('Z'))
    ->with('As');
 ...
 }

它让我对 As

感到空白
[As] => Array
      (
      }

*****编辑 1****** 表详细信息
这是他们
表 A | 职位空缺 |编号 |标题 | city_id |类型 | company_id
表 B | 公司 |编号 |姓名 |网址

公司有很多职位空缺

表 C | 公司行业 |编号 |类型 | company_id |行业标识
并且可能是许多工业部门的一部分。
type 是 1 或 2,其中 1 表示主要,2 表示其他

表 D | 行业 |编号 |名称
所有行业名称的主表
例如。服务、时尚等

【问题讨论】:

  • @eep Patel 查看最后代码行的语法
  • 您已经有一段时间没有问过了,我不确定您是否找到了答案,但我注意到,在 Laravel-3 中,您只能在主模型类之后使用 with("eager_loading_method")。所以它应该像下面$output = C::with("As")->where('Z_id', "=", Input::get('Z' , '' ) ); 也有利于为查询 Z 添加默认值

标签: php laravel orm eloquent laravel-3


【解决方案1】:

hasManyThrough 的第三个参数是密切相关模型上的外键(B 这里),所以这就是你需要的:

public function As()
{
  return $this->hasManyThrough('A','B','C_id','B_id');
}

但是,根据 cmets,hasManyThrough 仅适用于 A hasOne/hasMany B, B hasOne/hasMany C。所以在你的情况下你不能使用它。

您可以这样做:

$c = C::where('Z_id','=',Input::get('Z'))->first();
$as = $c->b->as;

【讨论】:

  • 感谢您的回复。但是B没有C_id表C有外键B_id,它指的是B的id
  • 那你不能使用hasManyThrough。它仅适用于A hasOne/hasMany B, B hasOne/hasMany C。而不是那些模型,最好展示你的表格,我会给你正确的 Eloquent 设置。
  • 将表格详细信息添加到编辑 1
  • 好的,我的建议已经在编辑中了。现在只需说出您想要实现的目标,因为原始问题已经解决,但我想您的问题仍然存在。
  • 我想要例如。所有具有 Industry.id = 180 、 JobOpenings.city_id = 2 和 JobOpenings.type = "全职" 的 JobOpenings 所以基本上我想列出一个城市的所有职位空缺,其中公司在选定的行业部门。另外,由于 CompanyIndustry 中也有行业 id,所以我想到了直接使用 CompanyIndustry 模型。
猜你喜欢
  • 1970-01-01
  • 2018-10-08
  • 2015-04-04
  • 2013-01-22
  • 2021-05-06
  • 2021-10-02
  • 2018-09-18
  • 2016-04-14
  • 1970-01-01
相关资源
最近更新 更多