lundi 29 juillet 2019

laravel select certian column of table with query on relation table

user can send a parameter for search , it can be city name or hotel's name. i want to search that in hotel table and city table then and i want to send back only hotel name and city name in any result in response. with my query it only return name of hotel but city's data is null, why? hot can i handle this?

hotel and city have relation

in Hotel Model i have:

  public function city()
    {
        return $this->belongsTo(City::class);
    }

in city model:

  public function hotel()
    {
        return $this->hasMany(Hotel::class);
    }

my query in related controller:

$hotels = Hotel::with('city')->select('name')->where('name', 'like', '%' . $request->target . '%')
                ->orWhereHas('city', function ($query) use ($request) {
                    $query->where('name', 'like', '%' . $request->target . '%');
                })
                ->orderBy('id')
                ->take(10)->get();
return response()->json(['result' => $hotels]);

and response is :

{"result":[{"name":"venus","city":null}]}



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

Aucun commentaire:

Enregistrer un commentaire