laravel:从数据库中选择

t40tm48m  于 2021-06-23  发布在  Mysql
关注(0)|答案(1)|浏览(290)

在我的laravel应用程序中,我有两个表:

Projects
- id
- user_id 
- name
- etc...

Images
- id
- project_id
- url

如何实现它,显示每个用户拥有的所有项目和所有连接的图像(每个项目最多可以有20个图像(存储在ftp中)和链接在字段url中-表“projects”中的项目id将保存在字段images.project\u id中)?
我学到了,我可以展示这样的项目:

$projects = DB::table('projects')->where('user_id','=',$user->id)->get();

我试着

$images = DB::table('images')->where('project_id','=',$projects->id)->get();

但我收到一条错误信息:

Property [id] does not exist on this collection instance.

我错过了什么?谢谢你给我指出了正确的方向:-)
谨致问候,
斯特凡

wz1wpwve

wz1wpwve1#

对于你的问题,我建议用雄辩的方式,比如建立你的模型

class Project extends Model
{
    public function images()
    {
        return $this->hasMany(\App\Models\Image::class, 'project_id');
    }

    public function user()
    {
        return $this->belongsTo(\App\Models\User::class, 'user_id');
    }
}

class Image extends Model
{
    public function project()
    {
        return $this->belongsTo(\App\Models\Project::class, 'project_id');
    }
}

现在要查找带有图像的项目,可以按以下方式进行查询:

$projects = Project::with('images')->get();

中的每个对象 $projects 将收集它们的相关图像。
为您可以使用的用户添加筛选器 whereHas 关系论

$projects = Project::with('images')
                    ->whereHas('user', function ($query) use ($user) {
                        $query->where('id', '=', $user->id);
                    })->get();

相关问题