问题
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