mysql_num_rows in laravel 5



im试图为管理员提供一个选项,以选择在网站中显示类别的顺序。

因此,在控制面板中,每个类别的标题旁边都有一个向上箭头和向下箭头。如果他点击向下,则该类别按一个顺序向下。

我的问题是,如果类别在底部,在顺序的最后一个,并且管理员单击向下箭头,我想显示一个错误。

所以我在我的控制器上做了这样的事情:

    /*
 * Category order - down
 */
public function down($id)
{
    $cat = Cat::findOrFail($id);
    $new_location = $cat->location + 1;
    $num_cats = count(Cat::all()); //number of cats
    //die($num_cats);
    if ($new_location >= $num_cats)
    {
        return Redirect::route('pages')->with('msg', 'it is allready the last category');
    }
    $cat->where('location', '=', $new_location)->update(['location' => $cat->location]); //moving the old category
    $cat->where('id', '=', $id)->update(['location' => $new_location]); //updating the new location
    return Redirect::route('pages')->with('msg', 'the cat has been updated');
}

但是$num_cats变为null。

有什么想法吗?我该如何获取所有类别的编号?

编辑:型号

class Cat extends Model { 
    public $timestamps = false; 
    protected $fillable = array( 'name', 'location', 'slug' ); 
    /*
     * A categorey has many pages 
     */ 
    public function pages() { 
        return $this->hasMany('AppPage')->where('solo', '!=', 1); 
    }
}

感谢

建议您像这样做计数$num_cats = Cat::count()

因为Cat::all()的返回是IlluminateDatabaseEloquentCollection 的对象

你需要知道函数计数 int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )

Cat::count(); SQL:SELECT count(*) as aggregate FROM "cats";需要更少的内存。

Cat::all()->count(); SQL:SELECT * FROM "cats";需要更多内存。

您可以使用其中任何一个来获取计数:

$num_cats = count(Cat::all());

$num_cats = Cat::all()->count();

$num_cats = count(Cat::all()->toArray());

最新更新