gpt4 book ai didi

Laravel 多态关系与自定义键

转载 作者:行者123 更新时间:2023-12-01 08:01:26 24 4
gpt4 key购买 nike

我在让多态关系在 Laravel 中工作时遇到了一些问题


Vacations
id
name

Posts
id
name

Images
id
type_id
type
Images.type_id链接到 posts.idvacations.id Images.type要么是 postvacation
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

当我运行这个“原始”并替换 "App\Vacation" 时与 vacation然后我得到我的结果。

将命名空间类名传递给原始 sql 查询是否正常?

我试过改变 Images.type从复数到单数的值,但它仍然失败。

我究竟做错了什么?

编辑:这是 Laravel 5.4,最新版本 afaik。

最佳答案

就其值(value)而言,无需更新数据库即可实现您想要的目标。

我在旧数据库上遇到了同样的问题,我通过将以下内容添加到 bootstrap/app.php 来修复它.

\Illuminate\Database\Eloquent\Relations\Relation::morphMap([
'vacation' => \App\Vacation::class,
'post' => \App\Post::class
]);

关于Laravel 多态关系与自定义键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43612399/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com