错误消息:http://puu.sh/d4l0F/5b0ac07e68.png
我什至在尝试创建关联之前保存了 $transportation 对象。我已经验证了 $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');
}
}
最佳答案
我有一个类似的问题。我犯了一个愚蠢的错误,没有在关系方法中添加“返回”!
确保您返回关系...显然这将不是 工作:
public function medicineType()
{
$this->belongsTo('MedicineType', 'id');
}
这是正确 道路:
public function medicineType()
{
return $this->belongsTo('MedicineType', 'id');
}
容易错过,难调试...
关于laravel - 在非对象上调用成员函数 associate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27116924/