Siddharth
Siddharth

Reputation: 1769

Select specific number of Random Rows from Database after Joining the tables - Laravel 5.1

Hi my database structure is as follows:

Table: articles

id | category_id(fk) | title | description | image

Table: categories

id | name

Table: domain_category

id | domain_id(fk) | category_id(fk)

Now from above Tables. I need only 8 Random Rows from table articles where domain_id = $dynamic_domain_id

What I've tried is as follows:

$randomArticles = Article::select("articles.*")
                        ->join('categories', 'categories.id', '=', 'articles.category_id')
                        ->join('domain_category', 'domain_category.category_id', 'categories.id')
                        ->where('domain_category.domain_id', $domain->lander_domain_id)
                        ->orderBy(DB::raw('RAND()'))->take(8)->get();

But I'm getting an error and not getting proper result. Thanks in advance.

Upvotes: 1

Views: 218

Answers (1)

Tim Biegeleisen
Tim Biegeleisen

Reputation: 521804

The only syntax error which jumps out at me is that you are missing an '=' parameter in your second join() function call. Try using this query instead:

$randomArticles = Article::select("articles.*")
                        ->join('categories', 'categories.id', '=', 'articles.category_id')
                        ->join('domain_category', 'domain_category.category_id', '=', 'categories.id')
                        ->where('domain_category.domain_id', $domain->lander_domain_id)
                        ->orderBy(DB::raw('RAND()'))->take(8)->get();

Upvotes: 2

Related Questions