Laravel的“一对多”关系似乎是相反的

问题描述 投票:0回答:3

我在一对多关系和口才方面挣扎。我有活动(如演出活动中),也有位置。每个事件都绑定到一个位置,但是每个位置都可以用来承载许多事件。 (一个)位置到(许多)事件。

这是我的模特:

class Iaevent extends Eloquent {
  public static $timestamps = true;
  public function locations() {
    return $this->has_one('Location');
  }
}

class Location extends Eloquent {
  public static $timestamps = true;
  public function iaevents() {
    return $this->has_many('Iaevent');
  }
}

如果我尝试回显:

echo $iaevent->locations()->first()->company;
//or
Iaevent::find(1)->locations()->first()->company;

我收到错误:

Unknown column 'iaevent_id' in 'where clause'
SQL: SELECT * FROM `locations` WHERE `iaevent_id` = ? LIMIT 1

现在...'iaevent_id'不在locations表中。而是将“ location_id”放在“ ievents”表中,因为一个位置可以适用于许多事件,但绝不能相反。我在这里做错了什么?

在Laravel论坛上,有人建议在我的Iaevent模型中将“ has_one”替换为“ belongs_to”。当我这样做时,我得到一个错误Trying to get property of non-object

以另一种方式用echo Location::find(1)->iaevents()->first()->name;测试关系很好。

laravel eloquent laravel-3
3个回答
1
投票

该事件属于该位置。

public function location()
{
    return $this->belongs_to( 'Location' );
}

$location = $event->location()->first();

if ( $location )
    $location->name;

“具有一个”关系用于一对一关系。说事件有一个location_id,但您只希望它是一对一的,而不是一对多的。在这种情况下,该位置只有一个事件,而该事件属于一个位置。


0
投票

具有正确的功能,因为它仅返回一个外来元素,但是has_many函数返回一个数组,因此您必须像对数组进行索引一样,正确的使用方式将是]]

Iaevent :: find(1)->位置[0]->公司;


0
投票

我必须指定“外部表”键,例如返回$ this-> has_one('Location','id');

© www.soinside.com 2019 - 2024. All rights reserved.