简体   繁体   中英

laravel 4 how to order and join by eloquent

Im new in Laravel 4, and right now im coding for small project, i use laravel as framework to build my website, but my code i always wonder it's optimize or not because in my model i just wrote:

Category Model

     public function parents()
    {
        return $this->belongsTo('Category', 'cat_father');
    }

     public function children()
    {
        return $this->hasMany('Category', 'cat_father');
    }

}

Post Model:

<?php
class Post extends BaseModel{
    public $table = "post";
    protected $primaryKey = 'idpost';

     public function Category()
    {
        return $this->belongsTo('Category', 'cat_id');
    }



}

because i didn't know how to join 2 tables in laravel 4, i have a condition is find all post from my categories, which it hadn't belong to category name "Reunion", but i didn't know how to do that, therefore i wrote 2 lines code for that purpose (im not sure wrote code in controller is best way but i didn't know how to call method from Model to controller and get return value)

My method from controller for select all post, it hasn't belong to category name "Reunion"

public function getAllPostView()
    {       
        $getCat = Category::where('cat_name','=', 'Reunion')->firstOrFail();                            
        $post = Post::where('cat_id', '!=', $getCat->idcategory)->get();
        return View::make('layouts.post')->with('post',$post);
    }   

My question, my code is optimize when i wrote it in controller? and how to wrote it in model and get parameter for passing it to controller and use it to view. second question is how to order "POST" because some cases post need to be ordered from new to old

could just use simple joins

public function getAllPostView()
{       
    $getCat = Category::where('cat_name','=', 'Reunion')  
            ->join('post','post.cat_id', '!=','Category.idcategory')->get();
    return View::make('layouts.post')->with('post',$post);
}   

Look out for same field names in both the tables if so can use select

$getCat = Category::select('Category.idcategory as cat_id','Category.cat_id as pos_id','many other fields')
               // 'as cat_id' not required for unique field names
            ->join('post','post.cat_id', '!=','Category.idcategory')
            ->where('cat_name','=', 'Reunion')  
            ->get();

This is how you do it:

$exclude = 'Reunion';

$posts = Post::select('posts.*')->join('categories', function ($j) use ($exclude) {
  $j->on('posts.cat_id', '=', 'categories.idcategory')
    ->where('categories.name', '<>', $exclude);
})->get();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM