在非对象上调用成员函数associate()

时间:2014-11-25 00:45:16

标签: laravel laravel-4 eloquent

错误讯息:http://puu.sh/d4l0F/5b0ac07e68.png

我甚至在尝试创建关联之前保存了$ transport对象。我已经验证了$ transporation,$ from和$ to都是它们各自的对象,它们都是。

我确信我在这里错过了一些愚蠢的东西,但我没有想法。

我的代码:

class RideBuilder implements RideBuilderInterface
{
    public function create(Advance $advance)
    {
        $ride = new Ride;
        if($ride->validate(Input::all())) {
            $ride->save();

            $to = Location::find(Input::get('dropoffLocation'));
            $from = Location::find(Input::get('pickupLocation'));

            $transportation = new Transportation;
            $transportation->save();

            $transportation->transportable()->associate($ride);
            $transportation->to()->associate($to);
            $transportation->from()->associate($from);

            $event = new Event;
            $event->start = Input::get('ridePickUpTime');
            $event->save();

            $event->eventable->save($transportation);
            $event->subjectable->save($advance);
        } 
        return $ride;
    }
}

位置模型:

class Location extends Elegant
{
protected $table = 'locations';

public $rules = array(
    'label'         => 'required|min:2',
    'street'        => 'required',
    'city'          => 'required',
    'state'         => 'required',
    'type'          => 'required',
);

public function advance()
{
    return $this->belongsTo('Booksmart\Booking\Advance\Model\Advance');
}

public function locationable()
{
    return $this->morphTo();
}

}

运输模式:

class Transportation extends Elegant
{
    protected $table = 'transportations';

    public function event()
    {
        $this->morphOne('Booksmart\Component\Event\Model\Event');
    }

    public function start_location()
    {
        $this->belongsTo('Booksmart\Component\Location\Model\Location', 'start_location');
    }

    public function end_location()
    {
        $this->belongsTo('Booksmart\Component\Location\Model\Location', 'end_location');
    }
}

1 个答案:

答案 0 :(得分:24)

我有类似的问题。我犯了一个愚蠢的错误,就是不在关系方法中添加“return”!

确保你恢复关系......显然这将工作:

public function medicineType() 
   {
      $this->belongsTo('MedicineType', 'id');
   }

这是正确方式:

public function medicineType() 
   {
      return $this->belongsTo('MedicineType', 'id');
   }

容易错过,难以调试......