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

Dyl*_*rce 3 laravel eloquent laravel-4

错误消息: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;
    }
}
Run Code Online (Sandbox Code Playgroud)

位置型号:

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();
}

}
Run Code Online (Sandbox Code Playgroud)

运输模式:

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');
    }
}
Run Code Online (Sandbox Code Playgroud)

HPa*_*age 25

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

请确保您返回的关系......显然,这将无法正常工作:

public function medicineType() 
   {
      $this->belongsTo('MedicineType', 'id');
   }
Run Code Online (Sandbox Code Playgroud)

这是正确的方法:

public function medicineType() 
   {
      return $this->belongsTo('MedicineType', 'id');
   }
Run Code Online (Sandbox Code Playgroud)

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

  • 这只是为我节省了2个小时无用的调试时间. (3认同)