[英]Polymorphic relation on eloquent event
I have 2 classes, Coordinate
and Hunt
我有2个班级,
Coordinate
和Hunt
class Coordinate extends Model {
public function locatable(){
return $this->morphTo();
}
}
and 和
class Hunt extends Model {
public function coordinate() {
return $this->morphOne('App\Coordinate', 'locatable');
}
}
Then I create a new instance of the models using 然后我使用创建一个新的模型实例
$cord = new Coordinate;
$hunt = new Hunt;
$hunt->save();
$hunt->coordinate->save($cord);
Now I listen to the saved event of the Hunt
现在我听保存的
Hunt
事件
class HuntSaved {
use Dispatchable, InteractsWithSockets, SerializesModels;
public $hunt;
public function __construct(Hunt $hunt) {
dd($hunt->coordinate);
$this->hunt = $hunt;
}
}
The strange thing is that the dd
here returns null
. 奇怪的是,这里的
dd
返回null
。
I cannot save the Coordinate
first due too its locatable_type
and locatable_id
which are not null
in the database. 我也不能先保存
Coordinate
因为它的locatable_type
和locatable_id
在数据库中not null
。
My question is, how can I handle the saved event using native eloquent events and get the related model. 我的问题是,如何使用本机雄辩事件处理保存的事件并获取相关模型。
在您的关系中,您应该首先创建坐标,然后创建寻线。
$coordinate->hunt()->create(array());
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.