Laravel 与自定义键的多态关系
Laravel polymorphic relationships with custom keys
我在让多态关系在 Laravel
中工作时遇到了一些问题
表格
Vacations
id
name
Posts
id
name
Images
id
type_id
type
Images.type_id
链接到 posts.id
或 vacations.id
Images.type
是 post
或 vacation
Posts and Vacations 可以有很多图像,但每张图像只属于 1 个 Post 或 Vacation。
度假模特
namespace App;
use App\Vacation;
class Vacation extends Model
{
public function images()
{
return $this->morphMany('App\Image', 'imageable', 'type', 'type_id');
}
}
图片模型
namespace App;
use App\Image;
class Image extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
当我 运行 这样做时,我得到一个空数组,但有匹配的记录。
$vacation = Vacation::find(1);
dd($vacation->images);
我可以看到 Laravel 正在尝试 运行:
select * from `images` where `images`.`type_id` = 1
and `images`.`type_id` is not null
and `images`.`type` = App\Vacation
当我 运行 这个 "raw" 并将 "App\Vacation"
替换为 vacation
然后我得到我的结果。
将命名空间 class 名称传递给原始 sql 查询是否正常?
我已经尝试将 Images.type
值从复数更改为单数,但仍然失败。
我做错了什么?
编辑:这是 Laravel 5.4,最新版本 afaik。
加入假期class
这条线
protected $morphClass = 'vacation';
如果你想将模型名称设为假期
在 images
中,您的列 type
应包含型号名称,在您的情况下为 App\Vacation
或 App\Post
。
物有所值,无需更新数据库即可实现您想要的效果。
我在遗留数据库中遇到了同样的问题,我通过将以下内容添加到 bootstrap/app.php
来修复它。
\Illuminate\Database\Eloquent\Relations\Relation::morphMap([
'vacation' => \App\Vacation::class,
'post' => \App\Post::class
]);
我在让多态关系在 Laravel
中工作时遇到了一些问题表格
Vacations
id
name
Posts
id
name
Images
id
type_id
type
Images.type_id
链接到 posts.id
或 vacations.id
Images.type
是 post
或 vacation
Posts and Vacations 可以有很多图像,但每张图像只属于 1 个 Post 或 Vacation。
度假模特
namespace App;
use App\Vacation;
class Vacation extends Model
{
public function images()
{
return $this->morphMany('App\Image', 'imageable', 'type', 'type_id');
}
}
图片模型
namespace App;
use App\Image;
class Image extends Model
{
public function imageable()
{
return $this->morphTo();
}
}
当我 运行 这样做时,我得到一个空数组,但有匹配的记录。
$vacation = Vacation::find(1);
dd($vacation->images);
我可以看到 Laravel 正在尝试 运行:
select * from `images` where `images`.`type_id` = 1
and `images`.`type_id` is not null
and `images`.`type` = App\Vacation
当我 运行 这个 "raw" 并将 "App\Vacation"
替换为 vacation
然后我得到我的结果。
将命名空间 class 名称传递给原始 sql 查询是否正常?
我已经尝试将 Images.type
值从复数更改为单数,但仍然失败。
我做错了什么?
编辑:这是 Laravel 5.4,最新版本 afaik。
加入假期class
这条线
protected $morphClass = 'vacation';
如果你想将模型名称设为假期
在 images
中,您的列 type
应包含型号名称,在您的情况下为 App\Vacation
或 App\Post
。
物有所值,无需更新数据库即可实现您想要的效果。
我在遗留数据库中遇到了同样的问题,我通过将以下内容添加到 bootstrap/app.php
来修复它。
\Illuminate\Database\Eloquent\Relations\Relation::morphMap([
'vacation' => \App\Vacation::class,
'post' => \App\Post::class
]);