我正在尝试使用Laravel为小型服务开发后端。我选择这个框架的主要原因 - 它有点像Railsesque。
我在Laravel上找不到任何有关命名约定的资源,因此遵循Rails路由(单数形式的模型 - 类别,控制器 CategoriesController ,并根据数据库表 - 类别)。我首先创建了迁移,然后让它运行。它按照我的预期创建了4个数据库表。然后我从SQL转储文件中手动输入了一些记录。然后在模型中声明表名。 问题是,当我查询这些记录时,这些记录并没有反映在工匠控制台上。
我对php框架没有认真的经验,所以请详细解答:)
Psy Shell v0.5.2 (PHP 5.6.12 — cli) by Justin Hileman
>>> App\Subcategory::all();
=> Illuminate\Database\Eloquent\Collection {#692
all: [],
}
>>> App\Category::all();
=> Illuminate\Database\Eloquent\Collection {#694
all: [],
}
>>> App\Category::count();
=> 0
>>> App\Subcategory::count();
=> 0
模型定义
#########Category.php###########
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $table = 'categories';
protected $fillable = ['name', 'show_in_nav'];
public function subcategories() {
return $this->hasMany('App\Subcategory');
}
}
#######Subcategory.php########
...
class Subcategory extends Model
{
//
protected $table = 'subcategories';
protected $fillable = ['name', 'image_path', 'category_id'];
public function category() {
return $this->belongsTo('App\Category');
}
public function products() {
return $this->hasMany('App\Product');
}
}
#########Product.php###########
....
class Product extends Model
{
//
protected $table = 'products';
protected $fillable = ['name', 'image_path', 'subcategory_id', 'description'];
public function subcategory() {
return $this->belongsTo('App\Subcategory');
}
}
一些数据库记录
mysql> SELECT * FROM subcategories LIMIT 5;
+----+--------+-------------+------------------+
| id | name | category_id | image_path |
+----+--------+-------------+------------------+
| 1 | Lorem | 1 | /images/img1.jpg |
| 2 | Ipsum | 2 | /images/img2.jpg |
| 3 | Dolor | 1 | /images/img2.jpg |
| 4 | Amet | 4 | /images/img4.jpg |
| 5 | Fabula | 5 | /images/img3.jpg |
+----+--------+-------------+------------------+
5 rows in set (0.00 sec)
mysql> SELECT id FROM categories LIMIT 5;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
+----+
5 rows in set (0.03 sec)