Laravel 4 Eloquent:引用同一模型的多种关系方法


Laravel 4 Eloquent: multiple relationship methods referencing the same model?

我有如下DB表:

images:
id name url etc
places:
id image_id name url etc
image_place:
image_id place_id

位置和图像具有多对多的关系,但每个位置也被分配一个图像,该图像用作列表中的缩略图。因此,在一对多的关系中,一个地方可能"属于"一个图像。因此,我在Laravel 4:中尝试了这个

models/Place.php:

public function image() {
  return $this->belongsTo('Image');
}
public function images() {
  return $this->belongsToMany('Image');
}

但是当我尝试访问$place->image时,我得到了一个错误:"调用未知方法getResults()。"

我做了一些实验,发现了以下解决方法:

  1. 如果我删除images()方法,$place->image将按预期工作。我目前不使用images(),所以这是我目前的解决方案,但我当然希望两者都可用。

  2. 如果我将image()函数替换为:return image::where('id',$this->image_id)->first();然后我可以通过$place->image()访问该对象。但我不能急于加载,这很重要,因为我在结果的长列表中使用缩略图。另外,我不喜欢只为这一个属性使用method()语法。

我还尝试重命名这些方法,例如image()和photos(),但没有什么区别。

在Laravel中,用不同类型的关系访问同一个模型是不可能的,还是我错过了什么?

您的images()应该是hasMany,您有它作为belongsToMany。我假设您已经正确地构建了数据库模式。

假设

places表的列image_id用于您使用的单个图像。

图像表具有与图像相关联的位置的列place_id

public function image()
{
    return $this->belongsTo('Image');
}
public function images()
{
    return $this->hasMany('Image');
}