【问题标题】:Multiple relationships on same table同一张表上的多个关系
【发布时间】:2014-07-11 19:30:10
【问题描述】:

在我的属性模型中,我定义了这两个关系

public function images() {
    return $this->hasMany('Image')
        ->where('approved', '=', 1);
}
public function pending_images() {
    return $this->hasMany('Image')
        ->where('approved', '=', 0);
}

在我的控制器中,我创建了一个 Property 对象并尝试获取已批准和待处理的图像。

$images = $property->images;
$pending = $property->pending_images;

var_dump($images);
var_dump($pending);
exit;

$images 变量正如预期的那样是 Illuminate\Database\Eloquent\Collection

但是,$pending 只是 NULL

我尝试使用this answer 获取最后一个数据库查询,但似乎未执行的查询甚至没有被执行。 (最后一个查询运行有approved = 1,这是images 关系。)

我怀疑关系在同一张桌子上可能是个问题,但我被难住了。

【问题讨论】:

    标签: laravel laravel-4 eloquent relationships


    【解决方案1】:

    您需要将该关系重命名为 camelCase:

    public function pendingImages() {
       return $this->hasMany('Image')
         ->where('approved', '=', 0);
    }
    

    然后它将按预期工作,而且您可以通过任何一种方式访问​​它:

    $property->pending_images == $property->pendingImages;
    

    动态属性仅适用于 camelCased 方法,仅此而已。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-05-14
      • 2018-11-23
      • 2013-02-17
      • 1970-01-01
      相关资源
      最近更新 更多