dimanche 27 décembre 2015

Need help converting nested join query to Laravel Eloquent

need some assistance making a query work in Laravel.

I've tried this query outside laravel and it works:

SELECT t.* FROM stories AS t JOIN ( SELECT created_at FROM stories WHERE id = 126 ) AS o ON t.created_at = o.created_at AND t.id > 126 OR t.created_at < o.created_at ORDER BY t.created_at DESC LIMIT 30;

Explanation: Basically it's needed for pagination as when users go to the next page it would show them 30 stories that were created before the specified id. When I sort the stories by created_at they become random, so I need to get the next 30 rows after a specific row which I accomplished with the above query. 126 is the id of the last story on the previous page which will be a variable in the actual code.

So when I try to use it in Laravel Eloquent whatever I do I just cannot make it work.

I've tried

$result = App\Story::join(DB::table('stories AS last_story')->find($previous_last_post_id), function($join) { $join->on('stories.created_at', '=', 'last_story.created_at') ->where('stories.id', '>', 'last_story.id') ->orWhere('stories.created_at', '<', 'last_story.created_at'); }) ->get() Which gives me "ErrorException in Grammar.php line 39: Object of class stdClass could not be converted to string"

Changing the subquery to DB::table('stories AS last_story')->where('id', $previous_last_post_id)->get()

gives me "ErrorException in Grammar.php line 39: Array to string conversion"

Gave up and also tried raw query:

$result = DB::select("SELECT t.* FROM stories AS t JOIN ( SELECT created_at FROM stories WHERE id = 126 ) AS o ON t.created_at = o.created_at AND t.id > 126 OR t.created_at < o.created_at ORDER BY t.created_at DESC LIMIT 30") but that gave me "ErrorException in helpers.php line 469: htmlentities() expects parameter 1 to be string, array given"



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire