-
-
Save lhl722/17a4009d65891027a883b1946f32f6ba to your computer and use it in GitHub Desktop.
Laravel 5 Eloquent CheatSheet #laravel #eloquent
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Model:: | |
| /*Select*/ | |
| ->select('col1','col2') | |
| ->select(DB::raw('businesses.*, COUNT(reviews.id) as no_of_ratings, IFNULL(sum(reviews.score),0) as rating')) | |
| /*Query*/ | |
| ->where('column','value') | |
| ->where('column','LIKE','%'.$value.'%') | |
| ->orWhere('column','!=', 'value') | |
| ->whereIn('column',[1,2,3]) | |
| ->whereRaw('age > ? and votes = 100', array(25)) | |
| ->whereNotIn('id', function($query){ | |
| $query->select('city_id') | |
| ->from('addresses') | |
| ->groupBy('addresses.city_id'); | |
| }) | |
| ->whereRaw(DB::raw("id in (select city_id from addresses GROUP BY addresses.city_id)")) | |
| /*Joins*/ | |
| ->join('business_category',function($join) use($cats) { | |
| $join->on('business_category.business_id', '=', 'businesses.id'); | |
| }) | |
| ->leftJoin('reviews',function($join) { | |
| $join = $join->on('reviews.business_id', '=', 'businesses.id'); | |
| }) | |
| /*Eager Loading */ | |
| ->with('table1','table2') | |
| ->with(array('table1','table2','table1.nestedtable3')) | |
| ->with(array('posts' => function($query) use($name){ | |
| $query->where('title', 'like', '%'.$name.'%') | |
| ->orderBy('created_at', 'desc'); | |
| })) | |
| /*Grouping*/ | |
| ->groupBy('state_id','locality') | |
| ->havingRaw('count > 1 ') | |
| /*Cache*/ | |
| ->remember($minutes) | |
| ->rememberForever() | |
| /*Offset & Limit & Order*/ | |
| ->take(10) | |
| ->limit(10) | |
| ->skip(10) | |
| ->orderBy('id','DESC') | |
| /*Getters*/ | |
| ->find($id) | |
| ->findOrFail($id) | |
| ->first() | |
| ->firstOrFail() | |
| ->all() | |
| ->get() | |
| ->lists() | |
| ->paginate() | |
| ->count() | |
| ->count(DB::raw('distinct businesses.id')); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment