skip to Main Content

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:

  1. Get all the reviews linked to each mechanic like this $mechanic->reviews();
  2. 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


  1. You can define a relationship in mechanic model using pivot table – mechanic_review table to return mechanic reviews.

    public function mechReviews()
    {
        return $this->hasMany(Review::class, 'mechanic_review','mechanic_id','review_id');
    }
    

    Now you can access mechanic reviews using $mechanic->mechReviews .

    Login or Signup to reply.
    1. To get all the reviews linked to each mechanic, you can define a reviews() method on the Mechanic model that uses the belongsToMany relationship. then you can access all the mechanics of a single workshop along with the reviews using WITH.
    2. to get the high rated mechanics you need to add an attribute in reviews table which should be integer type so that you can get the number of rating per mechanic. Then you can get the single or multiple mechanics by getting the list of mechanics from workshops with highest rating from reviews table and you can limit it to any number from 1 to 10 or of your choice.
      $mechanics = Mechanic::withCount(‘reviews’)->orderByDesc(‘ratings’)->take(10)->get();
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search