文档里模型一对一 (多态) 自定义列无效
问题:看文档时发现按照文档写的不生效!
操作步骤:
- 【位置】–> 模型关联->多态关联->一对一 (多态)
文档介绍如下:
自定义列
/**
* 获取 image 实例所属的模型
*/
public function imageable()
{
return $this->morphTo(__FUNCTION__, 'imageable_type', 'imageable_id');
}
按文档,分别创建了3个模型test_goods,test_users,test_images,
test_image提供图片;
test_goods.php:
public function image()
{
return $this->morphOne(test_images::class,'imageable');
}
test_images.php:
public function imageable()
{
return $this->morphTo(__FUNCTION__,'from_type','from_id');
}
我以为这里传入了参数: FUNCTION,’from_type’,’from_id’
那么test_images表就可以这么定义字段了
我以为匹配的时候就会按from_id匹配了,特意吧imageable_id的1改成111,2改成222让他默认无法匹配。
但是新定义的也无法匹配。
关键来了: 改test_goods.php代码
test_goods.php:
public function image()
{
return $this->morphOne(test_images::class,'from');
}
将 imageable 改成 from 发现可以了。。。。
然后再将from随意改成 from_laravl 报错提示:
结论:
是不是文档的代码
test_images.php:
public function imageable()
{
return $this->morphTo(__FUNCTION__,'from_type','from_id');
}
这段无法修改默认的字段呢?
而且我把这段代码写成如下:
test_images.php:
public function imageable()
{
return $this->morphTo('aaa','bbb','ccc');
}
也可以运行!!!为什么? 错在哪里?
第一个参数
name
是关联关系名称,你后面的参数type
是 from_type,id
是 from_id,这里的name
就应该是 from多看文档吧。。。,对了 ,感叹号不要用在标题和疑问上面。
看文档时发现按照文档写的不生效!我也是这个问题,定义的一对一多态,获取的关联为null ?