How to rewrite SQL query in Laravel?

六月ゝ 毕业季﹏ 提交于 2019-12-10 12:16:25

问题


I use the following Query Builder:

$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();

How to rewrite this query using short form with:

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

Because, in this query builders adds conditon and where delete_at NOT null in the end, and it works wrong.

Relations between tables:

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

1) Announcement can has one or more categories (Announcement has many Announcement_category)

2) User can has one or more categories

3) User_category is related with Announcement_category by category_id = category_id


回答1:


You should define the relationship between Announcement and AnnouncementCategory first

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

Then, add condition to the relationship as you go or even set it up in the relationship function.



来源:https://stackoverflow.com/questions/42458971/how-to-rewrite-sql-query-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!