php 如何在 Laravel 5 中调用模型?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28607829/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:58:48  来源:igfitidea点击:

How to call models in Laravel 5?

phplaravellaravel-5

提问by user1692333

So, in L5 I created folder like app/Models/Blogwhere is file Posts.phpwhich looks like:

因此,在 L5 中,我创建了文件夹,例如app/Models/Blog文件所在的位置Posts.php,如下所示:

<?php namespace App\Models\Blog;

use Illuminate\Database\Eloquent\Model;

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

After it I executed composer dumpand then in my controller:

之后我执行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);
    }
}

It throws me an error:

它给我一个错误:

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

回答by Kussie

Try changingthis:

尝试改变这个:

use Models\Blog\Posts as Posts;

To this:

对此:

use App\Models\Blog\Posts;

回答by Peon

In Laravel 5.2 it's just:

在 Laravel 5.2 中,它只是:

use App\Blog;

or

或者

use App\Blog\Posts;

回答by Ema.H

You need to check two points :

您需要检查两点:

  1. the namespacehave to be in first
  2. the using must be use App\Models\Blogin your case
  1. namespace必须在第一
  2. 使用必须use App\Models\Blog在你的情况下

Like this :

像这样 :

<?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);
    }
}

(tested with Laravel 5.4)

(用 Laravel 5.4 测试)

回答by maartenpaauw

Change the following

更改以下内容

class Posts extends Model {

to

class Posts extends \Eloquent {