我们如何将codeigniter代码转换为laravel

时间:2015-12-18 16:14:47

标签: php codeigniter laravel-5.1

查看代码

我们如何将此代码转换为laravel

<div class="property-grid">
          <ul class="grid-holder col-3">
            <?php foreach ($r as $row) : ?>
              <li class="grid-item type-rent">
                <div class="property-block"> <a href="<?=base_url()?>controller/buy_and_sell/<?= $row->sub_id; ?>" class="property-featured-image"> <img src="<?=base_url()?>real/images/background-images/sub-category-images/<?= $row->sub_cat_images;?>" alt=""> <span class="images-count"><i class="fa fa-picture-o"></i> 2</span></a>
                  <div class="property-info">
                    <h4><a href="<?=base_url()?>controller/buy_and_sell/<?= $row->sub_id; ?>"><?= substr($row->sub_cat_name, 0, 24);?></a></h4>
                    <span class="location">NYC</span>
                    <div class="price"><strong>Records</strong>
                      <span>
                        <?php 
                        $data = $this->model->get_product_count($row->sub_id);
                          //echo array_shift($data);
                        echo $data['count'];
                        ?>
                      </span>
                    </div>
                  </div>
                </div>
              </li>
            <?php endforeach; ?>
          </ul>
        </div>

型号代码

function get_product_count($id){
    $query = $this->db->query("select COUNT(sub_id) AS count FROM products WHERE products.sub_id = $id");
    return $query->row_array();
}

此代码转换为laravel ////////////////////////////////////////////////// ///////////////////////

此代码转换

<span>
                        <?php 
                        $data = $this->model->get_product_count($row->sub_id);
                          //echo array_shift($data);
                        echo $data['count'];
                        ?>
                      </span>

1 个答案:

答案 0 :(得分:1)

将此CI代码转换为laravel非常简单。只是你应该了解laravel MODEL(Eloquent ORM)概念和routes的基本知识。

您必须首先制作模型,只需要一个简单的查询来获取产品数量,或者您可以直接使用查询构建器而不是使用模型。

使用模型,您可以执行以下操作:

Product::where('sub_id',$id)->count();

此处Product是模特。

如果要使用查询构建器,则等效查询将为:

DB::table('products')->where('sub_id',$id)->count();

这里products是数据库表。

您必须知道的另一件事是编写和使用路由来指向控制器中的特定功能,带或不带参数。你的代码在视野中并不清楚,所以我举个例子:

class ProductController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        // your code here
    }
}

如果这是您的控制器,那么您可以在routes.php文件中写入路由以指向该索引函数:

Route::get('/index','ProductController@index');

然后您可以在视图文件中使用此路由将用户重定向到该索引函数。

要转换上一个代码,我们可以将该计数值传递到该视图文件中 或者我们可以在我们的模型中调用一个函数来计算sub_id,

public function getCount($id)
{
    return $this->where('sub_id',$id)->count();
}

我们可以从视图文件中调用

$product->getCount($sub_id)

我们可以使用刀片语法来显示值而不是echo,如:

{!! $count !!} or {!! $product->getCount($sub_id) !!}

我希望您有一些想法将CI代码转换为laravel。如果您仍然感到困惑,可以参考官方documentation。获得这些东西不会花费太多时间,因为CI和Laravel中的过程非常相似。