如何在Laravel中重写SQL查询?

时间:2017-02-25 17:04:25

标签: laravel laravel-5.4

我使用以下查询生成器:

$res = Announcement::whereExists(function ($query) {
                $query->select(DB::raw(1))
                    ->from('announcement_category')
                    ->join('user_category', 'user_category.category_id', '=', 'announcement_category.category_id')
                    ->where('user_category.user_id', 1)
                    ->where('announcement_category.announcement_id', '=', 'announcements.id')
                    ->whereNull('deleted_at');
            })->get();

如何使用短格式with重写此查询:

Announcement::with("announcement_category")...

因为在这个查询中,构建器最后添加了条件和where delete_at NOT null,并且它的工作错误。

表之间的关系:

Announcement           Announcement_category          User_category
_____________          ____________________________   _______________
id | name             announcement_id | category_id   user_id | category_id

1)Announcement可以有一个或多个类别(Announcement has many Announcement_category)

2)用户可以有一个或多个类别

3)User_categoryAnnouncement_category

category_id = category_id相关

1 个答案:

答案 0 :(得分:0)

您应首先定义Announcement和AnnouncementCategory之间的关系

public function announcement_category() {
 return $this->hasMany(AnnouncementCategory::class, 'announcement_id')
}

然后,在你去的时候为关系添加条件,甚至在关系函数中设置它。