lundi 27 août 2018

laravel eloquent hasmany or hasmany trough

I have structure like this

table events with column id  
table users with column id 
table topics with columns id, event_id, user_id

what I want is to get API with

events{
  id, 
  topics{all topics here}, // this part is working
  users{users relevant to single topic here} // not sure how to do this
}

my Controller looks like this

class EventsController extends Controller
{
    public function index(Request $request)
    {
        $events = Event::with('topics', 'users')->get();
        $response = ['events' => $events];
        return response($response, 200);
    }...

and my model is this

class Event extends Model
{
    protected $table = 'events';
    //

    public function topics()
    {
        return $this->hasMany(Topic::class, 'event_id');
    }

    public function users()
    {
       return $this->hasMany(User::class, 'id');
    }
}

but this function users from the model is returning only users which event.id is in displaying so if event id is 2 I will get only user with id 2

can I somehow write custom query inside Model? or return all relevant users? or simply return all users, but inside that event response?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire