简体   繁体   中英

DB Laravel get and first in same time

I want to show only one result from "links, tags, pages", "->first()", but, I want to show multiple results from "comments", "->get()", separate it in one array, and send to view, how can I do this?

    $link = DB::table('links')
            ->join('tags', 'tags.id', 'links.tag')
            ->join('pages', 'pages.id', '=', 'links.page_id')
            ->leftJoin('comments', 'comments.link_id', '=', 'links.id')
            ->select('links.photo', 'links.id', 'links.description', 'links.country', 'links.url', 'links.suggestions', 'links.shares', 'links.friendly_url', 'links.page_id', 'links.sponsored', 'links.clicks', 'links.title', 'tags.color', 'tags.id as tag_id', 'tags.name', 'pages.name as p_name', 'pages.description as p_description', 'pages.id as p_id', 'pages.followers', 'pages.links', 'pages.friendly_url as p_friendly_url', 'pages.photo as p_photo')
            ->where('links.friendly_url', $id)
            ->first();


    return view('site.link', compact('link'));

DD($link);

0 => Link {#291 ▼
      #relations: array:3 [▼
        "page" => Page {#295 ▶}
        "tag" => Tag {#289 ▶}
        "comments" => Collection {#292 ▼
          #items: array:2 [▼
            0 => Comment {#299 ▶}
            1 => Comment {#301 ▶}
          ]
        }
      ]

You could use Eloquent. Define relationships:

public function page()
{
    return $this->belongsTo(Page::class);
}

public function tag()
{
    return $this->belongsTo(Tag::class, 'tag');
}

public function comments()
{
    return $this->hasMany(Comment::class);
}

And do this:

Link::with('page', 'tag', 'comments')->where('friendly_url', $id)->first()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM