eloquent - Searching data of laravel meta table of type metable -
i have 3 tables users, articles , metas. had defined morphto() , morphtomany() according laravel 5.3 doc , can pull particular property of either user or article defined in metas table such firstname or lastname or coordinate.
now having difficulties writing correct model search these properties e.g search user's firstname or lastname or both.
<u>user table</u> id. username. password 1. test. testpass <u>article</> id. title. slug 1. article title. my-article-title
metas table
id. key. value. metable_id metable_type 1 firstname ade 1 app\user 2. content. sample article 1. app\article 3. lastname. keon. 1. app\user
meta.php extract
public function metable() { return $this->morphto(); }
user.php extract
public function meta() { return $this->morphtomany('app\user', 'metable'); } public function getname() { $user = user::find($this->id); $metadata = $user->meta()->wherein('key', ['firstname', 'lastname']) ; dd($metadata); }
article.php extract
public function meta() { return $this->morphtomany('app\user', 'metable'); }
the getname function worked expected can't figure out how search of user metadata unlike conventional php/mysql table joins
dont know how whole polymorphic relationship in laravel new me found , used these:
public function getsearch() { return user::with(array('metas' => function($query) { $query->where('value', $query); })); }
or
public function getsearch() { return user::with('metas') ->wherehas('metas', function($query) { $query->where('value', '=', $query); }); }
i cant see or reason how join tables in laravel
here new search query
public function getresults(request $request) { $keyword = $request->input('query'); $filterone = $request->input('minage'); $filtertwo = $request->input('maxage'); $query = user::with(['meta' => function ($q) { $q->where('value', 'like', $keyword) ->orwhere(function ($q) { $q->wherebetween('value', [$filterone,$filtertwo]); }); }])->get(); dd($query); }
thanks contribution above, insufficient of push me harder readings , thinking, came across use()
function query shown below;
public function getresults(request $request) { $keyword = $request->input('query'); $filterone = $request->input('minage'); $filtertwo = $request->input('maxage'); if (isset($keyword)) { $query = user::with(['meta' => function ($q) use ($keyword,$filterone,$filtertwo) { $q->where('value', 'like', $keyword) ->wherebetween('value', [$filterone, $filtertwo]); }])->get(); } else { $query = user::with(['meta' => function ($q) use ($filterone,$filtertwo) { $q->wherebetween('value', [$filterone, $filtertwo]); }])->get(); } dd($query); }
this gives me result looking for; though not sure effect on performance when dealing large dataset guess that's next assignment.
Comments
Post a Comment