Marc Jansen
Marc Jansen

Reputation: 23

PHP Laravel Database: Get all entries from one table + more

My problem is a bit abstract, so I can't really explain.

I have a few tables: table 1 is called videos and the other tables are categories like Dell, HP, Acer etc.

In table 1 are videos which have auto_increment primary ID's 1,2,3,4 etc. Video number 1 is from Dell, number 2 is HP, number 3 is Dell again and 4 is Acer. Number 1 is also in table Dell as id 1, number 2 is in table HP as id 2, number 3 is in table Dell with id 3, and 4 is in acer as id 4.

public function showCategory($cat) {
    switch ($cat) {
        case 'dell':
            $dell = DB::table('dell')->get();
            $videoid = '';

            foreach ($dell as $video) {
                $videoid .= $video->videoid.',';
            }

            echo $videoid; // this is an echo (test)

            $videos = DB::table('videos')
                ->where('id', $videoid)
                ->orderBy('id', 'DESC')
                ->paginate(25);
            break;

        default:
            # code...
            break;
    }

    return view('index')->with(array('videos' => $videos));
}

At this point, the echo $videoid; will show me all id's like:

1,3,40,42,43,44,46,58,61,67,68,73,86,101,102,103,105,106,112,117,121,122,123,124,

(i have many entrys)

The problem is, that on the index page it only shows number 1. Has anyone an idea?

Upvotes: 2

Views: 84

Answers (1)

Niklesh Raut
Niklesh Raut

Reputation: 34914

Use whereIn for multiple ids and explode method to make array of ids

        echo $videoid; // this is an echo (test)
        $videoArray = explode("," , $videoid);
        $videos = DB::table('videos')->whereIn('id', $videoArray)->orderBy('id', 'DESC')->paginate(25);
        break;

Update :

You can also use simple join

    $videos = DB::table('videos as v')
            ->join('dell as d','d.videoid','=','v.id')
            ->orderBy('v.id', 'DESC')
            ->select('v.*')
            ->paginate(25);
    break;

Remove all other code inside case dell

Upvotes: 1

Related Questions