Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/251.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php Laravel中一对多多态关系中从数据库获取数据的问题_Php_Laravel - Fatal编程技术网

Php Laravel中一对多多态关系中从数据库获取数据的问题

Php Laravel中一对多多态关系中从数据库获取数据的问题,php,laravel,Php,Laravel,我在Laravel中有一对多多态关系,我正在尝试使用雄辩的查询获取数据。我有最喜欢的模型和最喜欢的表格 id user_id favoritable_id favoritable_type 1 17 1 App\Models\ProfileImage 2 10 1 App\Models\PostVideo this is some other model 和带有 id use

我在Laravel中有一对多多态关系,我正在尝试使用雄辩的查询获取数据。我有最喜欢的模型和最喜欢的表格

id   user_id   favoritable_id   favoritable_type
1       17           1          App\Models\ProfileImage
2       10           1          App\Models\PostVideo   this is some other model
和带有

id   user_profile_id   title   path
1         17           etc      etc
我需要从profile_images表中获取与favorites表中的数据对应的所有profile_图像。因此,配置文件\u图像中的id与favoritable\u id匹配,用户\u配置文件\u id与用户\u id匹配,favoritable\u类型与favorites表中的App\Models\ProfileImage匹配。感谢您的帮助。这是我的密码

控制器

public function getProfileImages()
{
    $profileimage = ProfileImage::whereColumn('id', 'favoritable_id')->first();
    // I AM BASICALLY STUCK HERE WITH $profileimage !!!

    $favoriteProfileImages = $profileimage->favorites()->where([
            'user_id' => auth()->id(),
            'favoritable_id' => $profileimage->id,
            'favoritable_type' => ProfileImage::class
        ])->get();

    return $favoriteProfileImages;
}

选项1

假设用户和收藏夹模型之间没有关系,获取当前登录用户在收藏夹表中具有条目的所有PostImage记录

$profileImages=Favorite::where('user\u id',auth()->id())
->与([
'favoritable'=>fn($query)=>$query->where('favoritable_type',ProfileImage::class)
])
->得到()
->拨弄(“有利的”)
->展平()
->全部();
选项2

假设用户有许多喜爱的记录-存在许多关系

类用户扩展模型
{
公共功能收藏夹()
{
返回$this->hasMany(收藏夹::类);
}
//…类代码的其余部分
}
通过用户模型获得结果

$profileImages=User::with([
“收藏夹”=>
fn($query)=>$query->where('favoritable_type',ProfileImage::class)->with('favoritable')
])
->其中('id',auth()->id())
->第一()
->最爱
->拨弄(“有利的”)
->展平()
->全部();

不太明白你想要什么。是否要获取已收藏的ProfileImage的所有记录,即收藏夹表中有记录。或者,您希望从收藏夹表中获取与当前登录关联的所有记录user@Donkarnash我想要在收藏夹表中为当前登录的用户设置一个条目的配置文件图像。用户和收藏夹之间的关系是什么?如果有的话?@Donkarnash在收藏夹模型中我有公用函数User(){return$this->belongsTo(User::class);}和收藏夹表中的用户id。