问题描述:

I am a CodeIgniter trying to adopt Laravel, however, I have been having a lot of problems understanding how to use Eloquent.

I suspect that if I could figure out how to translate some of my CodeIgniter Model methods to Laravel Eloquent I might be able to get on better. Hopefully, this will help others with the same problem.

Could anybody please rewrite the following from CodeIgniter to Eloquent:

public function get_products($product_id = NULL, $category_id = NULL, $limit = NULL)

{

$this->db->select('*, product.id AS product_id');

$this->db->from('product');

$this->db->join('product_unit', 'product.source_unit_id = product_unit.id', 'left');

$this->db->join('stock_levels', 'product.stock_level_id = stock_levels.id', 'left');

$this->db->join('categories', 'product.category_id = categories.cat_id', 'left');

if(isset($product_id)) {

$this->db->where('product.id', $product_id);

}

if(isset($category_id)) {

$this->db->where('product.category_id', $category_id);

}

if(isset($limit)) {

$this->db->limit($limit);

}

#$this->db->order_by('categories.cat_name', 'ASC');

$this->db->order_by('categories.cat_name', 'ASC');

$this->db->order_by('product.name', 'ASC');

$query = $this->db->get();

return $query->result_array();

}

网友答案:

Here's an approximate version of your query, there should be some things to tweak, but I hope you get the idea:

public function get_products($product_id = NULL, $category_id = NULL, $limit = NULL)
{
   $query = Product::leftJoin('product_unit', 'source_unit_id', '=', 'product_unit.id')
                    ->leftJoin('stock_levels', 'stock_level_id', '=', 'stock_levels.id')
                    ->leftJoin('categories', 'category_id', '=', 'categories.cat_id');

    if(isset($product_id)) {
        $query->where('product.id', $product_id);
    }

    if(isset($category_id)) {
        $query->where('product.category_id', $category_id);
    }

    if(isset($limit)) {
        $query->limit($limit);
    }

    #$this->db->order_by('categories.cat_name', 'ASC');
    $query->orderBy('categories.cat_name', 'ASC');
    $query->orderBy('product.name', 'ASC');

    dd( $query->toSql() ); /// this line will show you the sql generated and die // remove it to execute the query

    return $query->get()->toArray();
}
相关阅读:
Top