如何调用Laravel 5中的模型?

How to call models in Laravel 5?

所以,在 L5 中,我创建了类似 app/Models/Blog 的文件夹,其中文件 Posts.php 看起来像:

<?php namespace App\Models\Blog;

use Illuminate\Database\Eloquent\Model;

class Posts extends Model {
    protected $table = 'posts';
}

之后我执行了 composer dump 然后在我的控制器中:

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use Models\Blog\Posts as Posts;

class BlogController extends Controller {

    public function index()
    {
        $post = Posts::all()->toArray();

        dd($post);
    }
}

它抛出一个错误:

FatalErrorException in BlogController.php line 14: Class 'Models\Blog\Posts' not found

更改以下内容

class Posts extends Model {

class Posts extends \Eloquent {

尝试改变这个:

use Models\Blog\Posts as Posts;

为此:

use App\Models\Blog\Posts;

在 Laravel 5.2 中只是:

use App\Blog;

use App\Blog\Posts;

您需要检查两点:

  1. namespace 必须在第一个
  2. 在您的情况下,using 必须是 use App\Models\Blog

像这样:

<?php
namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use App\Models\Blog;

class BlogController extends Controller {

    public function index()
    {
        $post = Posts::all()->toArray();

        dd($post);
    }
}

(使用 Laravel 5.4 测试)