【问题标题】:Laravel eloquent one to many relationship in custom pivot tablesLaravel 自定义数据透视表中的一对多关系
【发布时间】:2015-08-16 08:34:09
【问题描述】:

我在 mySQL 数据库中有一些表,我使用 laravel 来管理对这些表的访问:

-places
   id
   name

-events
   id
   name

-event_place
   id
   event_id
   place_id

-event_dates
   id
   start_date
   end_date
   event_place_id

然后我为上面的表格创建了以下模型:

class Place extends Model {

   public function events() {
      return $this->belongsToMany('App\Models\Event', 'event_place', 'place_id', 'event_id')->withPivot('id');
   }

   public function newPivot(Model $parent, array $attributes, $table, $exists) {
      if ($parent instanceof Event) {
         return new EventPlace($parent, $attributes, $table, $exists);
      }
      return parent::newPivot($parent, $attributes, $table, $exists);
   }
}

class Event extends Model {

   public function places() {
      return $this->belongsToMany('App\Models\Place', 'event_place', 'event_id', 'place_id')->withPivot('id');
   }

   public function newPivot(Model $parent, array $attributes, $table, $exists) {
      if ($parent instanceof Place) {
         return new EventPlace($parent, $attributes, $table, $exists);
      }
      return parent::newPivot($parent, $attributes, $table, $exists);
   }
}

class EventPlace extends Pivot {

   public function event() {
      return $this->belongsTo('Event');
   }

   public function place() {
      return $this->belongsTo('Place');
   }

   public function eventDates() {
      return $this->hasMany('App\Models\EventDate', 'event_place_id');
   }
}

class EventDate extends Model {

   public function eventPlace() {
      return $this->belongsTo('App\Models\EventPlace', 'event_place_id', 'id');
   }
}

当我运行这段代码时:

$dates = App\Models\EventDate::find(1)->eventPlace->toJson();
dump($dates);

这个错误上升:

Argument 1 passed to Illuminate\Database\Eloquent\Relations\Pivot::__construct() must be an instance of Illuminate\Database\Eloquent\Model, none given, called in /Users/hamidzamani/Sites/mycity/vendor/laravel/framework/src/Illuminate/Database/Eloquent/Model.php on line 827 and defined

谁能帮帮我?!

【问题讨论】:

  • 每次进行更改,都必须退出并重新进入 Tinker。
  • 我得到同样的错误!您找到答案或解决方法了吗?
  • @zeratulmdq 评论是正确答案,请将其转换为接受答案

标签: php laravel eloquent


【解决方案1】:

每次进行更改时,都必须退出并重新进入 Tinker。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-09-27
    • 2023-02-05
    • 2018-09-23
    • 2019-10-19
    • 2015-02-10
    • 1970-01-01
    相关资源
    最近更新 更多