My product model like this :
<?php
...
class Product extends Model
{
...
protected $fillable = ['name','photo','description',...];
public function favorites(){
return $this->morphMany(Favorite::class, 'favoritable');
}
}
My favorite model like this :
<?php
...
class Favorite extends Model
{
...
protected $fillable = ['user_id', 'favoritable_id', 'favoritable_type'];
public function favoritable()
{
return $this->morphTo();
}
}
My laravel eloquent like this :
$q = $param['q'];
$query = Favorite->where('user_id', auth()->user()->id)
->with('favoritable');
if($q) {
$query->whereHas('favoritable', function ($query) use ($q) {
$query->where('name', 'like', "%$q%");
});
}
$query = $query->paginate(5);
return $query
If the script executed, there exist error like this :
Unknown column 'name'
How can I solve this problem?
whereHas() works basically the same as has() but allows you to specify additional filters for the related model to check.
How to define One to One relationship in Laravel? Details table migration would look like following (add columns shown below): add title, description columns. define foregin key constraint in details table because it refers to post table.
A one-to-one polymorphic relationship is a situation where one model can belong to more than one type of model but on only one association. A typical example of this is featured images on a post and an avatar for a user. The only thing that changes however is how we get the associated model by using morphOne instead.
Solved
I add this method :
public function product()
{
return $this->belongsTo(Product::class, 'favoritable_id')
->where('favorites.favoritable_type', Product::class);
}
in favorite model
And I change the laravel eloquent to be like this :
$query->whereHas('product', function ($query) use ($q) {
$query->where('name', 'like', "%$q%");
});
It works
Laravel 5.8
include new features for querying polymorphic relations.
The whereHasMorph()
make it possible to query polymorphic relationships with something like the following:
Comment::whereHasMorph('commentable', [Post::class, Video::class], function($query){
$query->where('title', 'foo');
})->get();
Which produces following query:
select * from "comments"
where (
(
"commentable_type" = 'App\Post' and exists (
select * from "posts"
where "comments"."commentable_id" = "posts"."id" and "title" = 'foo'
)
) or (
"commentable_type" = 'App\Video' and exists (
select * from "videos"
where "comments"."commentable_id" = "videos"."id" and "title" = 'foo'
)
)
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With