5

I would know if it's possible to retrieve the first element of relation with Eloquent.

This doesn't work:

$posts = Post::with(['medias' => function($q) {
    $q->where('type', 'landscape')
      // not working
      ->limit(1);
      // not working
      ->take(1);
      // not working
      ->first();
}])->get();

This is a one-to-many relation.

Thank you in advance !

KeizerBridge
  • 2,707
  • 7
  • 24
  • 37
  • What type of relation is this? – Jarek Tkaczyk Dec 17 '14 at 15:20
  • This is a one-to-many relation – KeizerBridge Dec 17 '14 at 15:22
  • 1
    Wrong link the first time, check again: Then read this [Get latest related model](http://stackoverflow.com/questions/24343738/getting-just-the-latest-value-on-a-joined-table-with-eloquent). Also you can find useful these 2: [n-per-parent](http://softonsofa.com/tweaking-eloquent-relations-how-to-get-n-related-models-per-parent/) and [count](http://softonsofa.com/tweaking-eloquent-relations-how-to-get-hasmany-relation-count-efficiently/) – Jarek Tkaczyk Dec 17 '14 at 15:28
  • Thank you for this link, it can do the job. But it looks a bit tricky. Is there a simplest way to this ? – KeizerBridge Dec 17 '14 at 15:30
  • Check the link again - first time I gave you wrong one for the `n-per-parent` which is tricky indeed. Now you have the one and only way linked - `hasOne`. There's no other way if you want to eager load this thing. – Jarek Tkaczyk Dec 17 '14 at 15:36
  • @JarekTkaczyk - You are indeed right. Post it as an answer so that it can be upvoted and accepted. BTW, nice work on your blog there! – Joseph Silber Dec 17 '14 at 15:42
  • yep post it as an answer Ok @JarekTkaczyk, thank you again, even if it's not what I expected, less tricky but not really intuitive. – KeizerBridge Dec 17 '14 at 15:51
  • @KeizerBridge Just upvote the one I linked, no need for duplicating the answers. – Jarek Tkaczyk Dec 17 '14 at 16:07
  • @JosephSilber Thanks mate. I'm working on a piece about Eloquent ins and outs exclusively, should be out in a few weeks. – Jarek Tkaczyk Dec 17 '14 at 16:17
  • @JarekTkaczyk - Cool. Keep up the good work. I just subscribed to your feed :D – Joseph Silber Dec 17 '14 at 16:25
  • @JarekTkaczyk - Any particular reason your site's RSS feed is truncated? Kind of a bummer :( – Joseph Silber Dec 17 '14 at 17:14
  • @JosephSilber You mean that only posts' teasers are in the feed, not whole content? – Jarek Tkaczyk Dec 17 '14 at 21:08
  • @JarekTkaczyk - Correct. You only get the full article by clicking through. Unfortunately that's a deal breaker. I usually read my feeds with no internet access :( – Joseph Silber Dec 17 '14 at 21:10

0 Answers0