vendredi 17 novembre 2017

Laravel 5.2 orderBy on two clauses, one using a leftJoin

I have two tables - canvas and canvas_details - a canvas can have multiple canvas_details.

TABLE 'canvas'(
    'id'
    'name'
    'canvas_type'
    'created_at'
    'updated_at')

TABLE 'canvas_details' (
    'id'
    'canvas_id'
    'block_number'
    'block_title'
    'color'
    'size'
    'notes'
    'image'
    'order'
    'created_at'
    'updated_at')

In my Controller I have a function:

public static function canvasList($id){
    $canvas_list = \DB::table('canvas')
    ->select(\DB::raw('distinct(canvas.id),canvas.name'))
    ->join('canvas_user','canvas.id','=','canvas_user.canvas_id')
    ->leftJoin('canvasdetails','canvas.id','=','canvasdetails.canvas_id')
    ->where('canvas_user.user_id',$id)
    ->orderBy('canvas.updated_at','desc')       
    ->get();
    return $canvas_list}

Which I am using to display a list of canvas names per user sorted on when the canvas was last updated.

When a canvas is created it does not initially have any canvas_details. Creating or updating associated canvas_details doesn't update the canvas updated_at field but will update the canvas_details updated_at field.

What I need to do is to also sort on when the canvas_details were last updated.

I would like to show a list of canvas names sorted desc on either the last updated canvas or the last updated canvas_details.

Considering a canvas may or may not have canvas_details - is there a way to add that sort depending on the presence of a canvas_details record?



from Newest questions tagged laravel-5 - Stack Overflow http://ift.tt/2zL7Yqz
via IFTTT

Aucun commentaire:

Enregistrer un commentaire