【问题标题】:laravel 4 how to order and join by eloquentlaravel 4 如何通过 eloquent 订购和加入
【发布时间】:2015-01-27 22:45:08
【问题描述】:

我是 Laravel 4 的新手,现在我正在为小型项目编码,我使用 laravel 作为框架来构建我的网站,但我的代码我总是想知道它是否优化,因为在我的模型中我刚刚写了:

类别模型

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

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

}

帖子模型:

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

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



}

因为我不知道如何在 laravel 4 中加入 2 个表,我有一个条件是从我的类别中找到所有帖子,它不属于类别名称“Reunion”,但我不知道如何为此,我为此编写了 2 行代码(我不确定在控制器中编写代码是最好的方法,但我不知道如何从模型调用方法到控制器并获取返回值)

我的控制器选择所有帖子的方法,它不属于类别名称“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);
    }   

我的问题,当我在控制器中编写代码时,我的代码是否已优化?以及如何在模型中编写并获取参数以将其传递给控制器​​并使用它来查看。 第二个问题是如何订购“POST”,因为某些情况下需要从新到旧订购帖子

【问题讨论】:

标签: php laravel-4 eloquent


【解决方案1】:

可以使用简单的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);
}   

注意两个表中的相同字段名称,如果可以使用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();

【讨论】:

  • 好吧,试试就知道了。
  • 我找不到你的代码和我的代码之间的任何区别,除了另一种方式
  • 因为:1你不懂sql,2你没试过。当你这样做时,不要在查询中输入limit,只是一个提示。
【解决方案2】:

这就是你的做法:

$exclude = 'Reunion';

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-07-07
    • 2016-01-20
    • 1970-01-01
    • 2017-12-07
    • 1970-01-01
    • 2014-11-25
    • 2019-07-18
    • 1970-01-01
    相关资源
    最近更新 更多