I have 3 tables users, articles and metas. I had defined the morphTo() and morphToMany() according to the laravel 5.3 doc and I can pull any particular property of either the user or article defined in the metas table such as firstname or lastname or coordinate.
Now am having difficulties writing the correct model to search these properties e.g a search for any user's firstname or lastname or both.
<u>User table</u>
id. username. password
1. Test. Testpass
<u>article</>
id. Title. Slug
1. My 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 as expected but I can't figure out how to do a search of the user metadata unlike the conventional php/mysql table joins
Dont know how as the whole polymorphic relationship in laravel is new to me but I found and used something like 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 to join the tables in laravel
here is my 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 for the contribution above, the insufficient of this actually push me harder to readings and thinking, I finally came across the use()
with function query as 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 the result am looking for; though am not sure the effect on performance when dealing with large dataset but then i guess that's my next assignment.