mercredi 18 janvier 2017

Filter results from a laravel collection based on the related record

I'm using http://ift.tt/1nTHlPf in my Laravel Project.

I have a Hotel object with a many to many relationships with Users.

I can query the relationship using this:

protected $searchable = [
    'columns' => [
        'hotels.nombre' => 10
    ],
    'joins' => [
        'hotel_user' => ['hotels.id' , 'hotel_id'],
        'users' => ['hotel_user.user_id', 'users.id']
    ]
];

The search returns something like this (json format)

 [
  {
    "id": 3,
    "nombre": "Paradisus Playa del Carmen La Esmeralda",
    "url_foto": "uploads/hotel/3/1484747239.jpg",
    "website_url": "http://ift.tt/2jLE0I7",
    "updated_at": "2017-01-18 13:47:44",
    "relevance": 60,
    "users": [
      {
        "id": 1,
        "first_name": "Alex",
        "last_name": "Angelico",
        "formatted_name": "Alex",
        "company": "ConexionBIZ",
        "title": "Director",
        "picture_url": "http://ift.tt/2iS26CV",
        "created_at": "2017-01-17 12:00:00",
        "updated_at": "2017-01-18 13:50:19",
        "pivot": {
          "hotel_id": 3,
          "user_id": 1,
          "created_at": null,
          "updated_at": null
        }
      }
    ]
  },

I want to filter all the hotels belonging to some particular user. I tried:

 $result = \App\Hotel::search($request->get('q'))->with([
            'users' => function($q) use ($user_id) {
                $q->where('users.id', '<>', $user_id);
            },
        ])->get();

But this returns the hotel without the related user. I need to remove the HOTEL (not just the USER) from the results.

How can I do this?

Thanks a lot!



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2jLM4ca
via IFTTT

Aucun commentaire:

Enregistrer un commentaire