-
Notifications
You must be signed in to change notification settings - Fork 101
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Get only one media #83
Comments
Hi @borisdamevin, If I understand correctly, you have a If all posts have media attached to that tag, then $media = Post::whereHasMedia($tag) // restrict to results with that media
->withMedia($tag) // eager load the media at that tag
->first() //only load one post result
->firstMedia($tag); //get the first media record attached to this post or $posts = Posts::withMedia()->get(); // load all posts
$media = $posts->filter(function($post) use ($tag) {
return $post->hasMedia($tag); //restrict to those that have media for that tag
})->firstMedia($tag); |
Yes. But The best way will not to create a |
Sorry, the second example above is missing a call to |
The filter don't work. He get the same media for all posts. You don't have an idea for filter |
Hi @borisdamevin, I not clear what your intention is here. From your description it sounds like you are trying to get a single media from a collection of mediables, but if that is not the case, can you be more descriptive of your needs? Are you trying to create a collection with one media record for each post? |
Hi, Yes I try to get only one media on each post. |
Ok, that wasn't clear from your initial message. This isn't really a Mediable concern, but with Laravel collection handling. $media = $posts
->filter(...) //as above, use if you want to exclude posts that do not have media at that tag
->map(function($post) use ($tag){
return $post->firstMedia($tag);
} |
I think what you're looking to do is only fetch from the database a single $PostsWithOneMedia = Post::with(['media' => function($q) {
$q->latest()->limit(1);
}])->get(); Or for a specific tag $tag = "uploaded";
$PostsWithOneMedia = Post::with(['media' => function($q) use ($tag) {
$q->wherePivot('tag', $tag)->latest()->limit(1);
}])->get(); |
I finally find the good with your help.
Thank for your help :). Sorry if my request was not clear. |
Hi,
I try to find a method to get only one media on
posts
collection and not all media attach on each post.For exemple :
A post has many media, all with same tag. I wanna get only one of them. I suppose we need to use the
join
method, but how ?Now a use
$posts = Post::with('media')->get();
, but I dont wanna all media.Thank you.
The text was updated successfully, but these errors were encountered: