I am working on a workshop mechanic directory for a client using Laravel 8 framework and he wants a feature to review the workshop and also select multiple mechanics who the client worked with.
Each Workshop have multiple reviews and each review can have same or different mechanics who works at the workshop.
Please help me figure out how to:
- Get all the reviews linked to each mechanic like this $mechanic->reviews();
- Find top rated mechanics from all workshops.
Please let me know how to make this work.
Thank you so much.
Below is the relationships I made so far and I am not able to figure out the points above.
workshops table
name, email, phone, address
mechanics table
name, email, phont, address, workshop_id
reviews table
name, review, comment, workshop_id, status (active,pending,rejected)
mechanic_review table (for attaching multiple mechanics to each review)
mechanic_id,review_id
Workshop model
public function reviews() {
return $this->hasMany('AppModelsreview');
}
public function mechanics() {
return $this->hasMany('AppModelsMechanic');
}
Mechanic model
public function workshop() {
return $this->belongsTo('AppModelsWorkshop');
}
Review model
public function workshop() {
return $this->belongsTo('AppModelsWorkshop');
}
2
Answers
You can define a relationship in mechanic model using pivot table – mechanic_review table to return mechanic reviews.
Now you can access mechanic reviews using $mechanic->mechReviews .
$mechanics = Mechanic::withCount(‘reviews’)->orderByDesc(‘ratings’)->take(10)->get();