php PHPStorm 无法识别 Laravel 5.0 中我的 Model 类的方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31830077/
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
PHPStorm is not recognizing methods of my Model class in Laravel 5.0
提问by Osman Goni Nahid
failed insert data into database, and all query class and Model class's method not found show in IDE (phpStrom) how can I solve it?
将数据插入数据库失败,并且在IDE(phpStrom)中找不到所有查询类和模型类的方法,我该如何解决?
here is my extended class (Post.php) here show error in latest and where method:
这是我的扩展类(Post.php),这里在最新和 where 方法中显示错误:
<?php namespace App;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Model;
class Post extends Model {
protected $fillable=[
'title',
'description',
'location',
'contact',
'type',
'published_at'
];
protected $date=['published_at'];
public function setPublishedAtAttribute($date)
{
$this->attributes['published_at'] = Carbon::createFromFormat('Y-m-d', $date);
}
/**
* @param $query
*/
public function scopePublished($query)
{
$query->where('published_at', '<=', Carbon::now());
}
public function scopeUnPublished($query)
{
$query->where('published_at', '>=', Carbon::now());
}
/**
* An post is owned by a user.
* @return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user(){
return $this->belongsTo('App\User');
}
}
and Here is my Controller class where i use it :
这是我使用它的控制器类:
<?php namespace App\Http\Controllers;
use App\Http\Requests;
use App\Http\Requests\CreatePostRequest;
use App\Post;
use Request;
use Illuminate\Support\Facades\Auth;
use Session;
class PostsController extends Controller {
//
public function __construct()
{
$this->middleware('auth');
}
public function index()
{
//return \Auth::user()->name;
$posts = Post::latest('published_at')->published()->get();
$latest= Post::latest()->first();
return view('tolet.index', compact('posts','latest'));
}
/**
* @param Post $post
* @return \Illuminate\View\View
* @internal param Articles $article
* @internal param Articles $articles
*/
public function show(Post $post)
{
return view('tolet.show', compact('post'));
}
public function create()
{
if (Auth::guest()) {
return redirect('tolet.index');
}
return view('tolet.create');
}
/**
* @param CreatePostRequest $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
*/
public function store(CreatePostRequest $request)
{
//validation
$this->createPost($request);
// flash('Your tolet has been created!')->important();
return redirect('tolet.index');
}
/**
* @param Post $post
* @return \Illuminate\View\View
* @internal param Articles $article
*/
public function edit(Post $post)
{
return view('tolet.edit', compact('post'));
}
/**
* @param Post $post
* @param CreatePostRequest $request
* @return \Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector
* @internal param Articles $article
* @internal param $id
*/
public function update(Post $post, CreatePostRequest $request)
{
$post->update($request->all());
return redirect('tolet.index');
}
/**
* sync up the list of tags in the database
*
* @param Post $post
*/
/**
* save a new post
*
* @param CreatePostRequest $request
* @return mixed
*/
private function createPost(CreatePostRequest $request)
{
$post = Auth::user()->posts()->create($request->all());
return $post;
}
}
回答by Tomá? Staník
If you want a class extending Model
to recognize Eloquent methods, just add the following in the top PHPDoc comment on the class:
如果你想要一个扩展Model
来识别 Eloquent 方法的类,只需在该类的顶部 PHPDoc 注释中添加以下内容:
@mixin Eloquent
Example:
例子:
<?php namespace App;
use Carbon\Carbon;
use Eloquent;
use Illuminate\Database\Eloquent\Model;
/**
* Post
*
* @mixin Eloquent
*/
class Post extends Model {
Note:Most of you probably are using ide-helperfor Laravel, therefore this @mixin
attribute is automatically generated for model Classes.
注意:你们中的大多数人可能正在为 Laravel使用ide-helper,因此该@mixin
属性是为模型类自动生成的。
回答by ruuter
Since methods where
, latest
, find
, findOrFail
and others does not exist in Model
class, but in Builder
and are loaded via magic methods, the IDE can not detect these.
由于方法where
,latest
,find
,findOrFail
和其他人不存在Model
阶级,但Builder
并通过魔术方法被加载,IDE无法检测到这些。
While the widely suggested laravel-ide-helperis great, it does not helpalso. There are multiple issuesand discussionsand workarounds on the subject, but all have its own problems.
虽然广泛推荐的laravel-ide-helper很棒,但它也无济于事。关于这个主题有多个问题、讨论和解决方法,但都有自己的问题。
Best solution I've found so far, IMHO is to downgrade severity if __magic methods are present in class. PhpStorm has this exact option in inspections settings.
迄今为止我找到的最佳解决方案,恕我直言,如果 class 中存在 __magic 方法,则降低严重性。PhpStorm 在检查设置中有这个确切的选项。
Check in Settings -> Inspections -> PHP -> Undefined -> Undefined method
This will not let you click on the method, but merely disables the annoying markup. Read more about severitiesor check this more expressive SO answer
签入Settings -> Inspections -> PHP -> Undefined -> Undefined method
这不会让您点击方法,而只是禁用烦人的标记。阅读有关严重性的更多信息或查看这个更具表现力的 SO 答案
回答by Amr El Massry
For anyone who came here for a solution, what worked for me is the solution in this StackOverflow:
对于来这里寻求解决方案的任何人,对我有用的是此 StackOverflow 中的解决方案:
PhpStorm laravel 5 method not found
specifically when I ran:
特别是当我跑:
Edit: to use this command you have to install ide-helper, run:
编辑:要使用此命令,您必须安装ide-helper,运行:
composer require --dev barryvdh/laravel-ide-helper
...
...
php artisan ide-helper:models
and answered "yes"
并回答“是”
after that methods are recognized.
在这些方法被认可之后。
回答by Patrioticcow
My class. The annotations will help PhpStorm to recognize those methods.
我的课。注释将帮助 PhpStorm 识别这些方法。
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Query\Builder;
/**
* @method static Builder where($column, $operator = null, $value = null, $boolean = 'and')
* @method static Builder create(array $attributes = [])
* @method public Builder update(array $values)
*/
class User extends Model
{
protected $table = 'users';
protected $fillable = [
'email',
'name',
'password',
];
}
回答by Michael Pawlowsky
A little annoying to add to all your models, but you can add the method to your models docblock. That will make it work properly in PHPStorm.
添加到所有模型中有点烦人,但您可以将方法添加到模型文档块中。这将使它在 PHPStorm 中正常工作。
/*
* @method static \Illuminate\Database\Query\Builder|\App\MyModelName where($field, $value)
*/
回答by Rawburner
I am new to laravel and all this issues with models and phpstorm are very weird. This is a big disadvantage. The solutions like adding @mixin Eloquent or running php artisan ide-helper:models didn't work for me. PHPStorm don't find Eloquent or \Eloquent. ide-helper:models don't add all useable static methods. So I came with an own base model which contains a php doc with all relevant model methods:
我是 laravel 的新手,模型和 phpstorm 的所有这些问题都非常奇怪。这是一个很大的缺点。添加@mixin Eloquent 或运行 php artisan ide-helper:models 等解决方案对我不起作用。PHPStorm 找不到 Eloquent 或 \Eloquent。ide-helper:models 不会添加所有可用的静态方法。所以我提供了一个自己的基础模型,其中包含一个包含所有相关模型方法的 php 文档:
<?php
namespace App;
use Closure;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Contracts\Pagination\Paginator;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Model as EloquentModel;
use Illuminate\Database\Eloquent\Builder as EloquentBuilder;
use Illuminate\Database\Query\Builder as QueryBuilder;
/**
* Class BaseModel
* @package App
* @method EloquentModel|Collection|null static $this find($id, $columns = ['*']) Find a model by its primary key.
* @method EloquentModel|EloquentBuilder|null first($columns = ['*']) Execute the query and get the first result.
* @method EloquentModel|EloquentBuilder firstOrFail($columns = ['*']) Execute the query and get the first result or throw an exception.
* @method Collection|EloquentBuilder[] get($columns = ['*']) Execute the query as a "select" statement.
* @method mixed value($column) Get a single column's value from the first result of a query.
* @method mixed pluck($column) Get a single column's value from the first result of a query.
* @method void chunk($count, callable $callback) Chunk the results of the query.
* @method \Illuminate\Support\Collection lists($column, $key = null) Get an array with the values of a given column.
* @method LengthAwarePaginator paginate($perPage = null, $columns = ['*'], $pageName = 'page', $page = null) Paginate the given query.
* @method Paginator simplePaginate($perPage = null, $columns = ['*'], $pageName = 'page') Paginate the given query into a simple paginator.
* @method int increment($column, $amount = 1, array $extra = []) Increment a column's value by a given amount.
* @method int decrement($column, $amount = 1, array $extra = []) Decrement a column's value by a given amount.
* @method void onDelete(Closure $callback) Register a replacement for the default delete function.
* @method EloquentModel[] getModels($columns = ['*']) Get the hydrated models without eager loading.
* @method array eagerLoadRelations(array $models) Eager load the relationships for the models.
* @method array loadRelation(array $models, $name, Closure $constraints) Eagerly load the relationship on a set of models.
* @method static EloquentBuilder where($column, $operator = null, $value = null, $boolean = 'and') Add a basic where clause to the query.
* @method EloquentBuilder orWhere($column, $operator = null, $value = null) Add an "or where" clause to the query.
* @method EloquentBuilder has($relation, $operator = '>=', $count = 1, $boolean = 'and', Closure $callback = null) Add a relationship count condition to the query.
* @method static EloquentBuilder find($value)
* @method static EloquentBuilder orderBy($column, $direction = 'asc')
* @method static EloquentBuilder select($columns = ['*'])
*
*
* @method static QueryBuilder whereRaw($sql, array $bindings = [])
* @method static QueryBuilder whereBetween($column, array $values)
* @method static QueryBuilder whereNotBetween($column, array $values)
* @method static QueryBuilder whereNested(Closure $callback)
* @method static QueryBuilder addNestedWhereQuery($query)
* @method static QueryBuilder whereExists(Closure $callback)
* @method static QueryBuilder whereNotExists(Closure $callback)
* @method static QueryBuilder whereIn($column, $values)
* @method static QueryBuilder whereNotIn($column, $values)
* @method static QueryBuilder whereNull($column)
* @method static QueryBuilder whereNotNull($column)
* @method static QueryBuilder orWhereRaw($sql, array $bindings = [])
* @method static QueryBuilder orWhereBetween($column, array $values)
* @method static QueryBuilder orWhereNotBetween($column, array $values)
* @method static QueryBuilder orWhereExists(Closure $callback)
* @method static QueryBuilder orWhereNotExists(Closure $callback)
* @method static QueryBuilder orWhereIn($column, $values)
* @method static QueryBuilder orWhereNotIn($column, $values)
* @method static QueryBuilder orWhereNull($column)
* @method static QueryBuilder orWhereNotNull($column)
* @method static QueryBuilder whereDate($column, $operator, $value)
* @method static QueryBuilder whereDay($column, $operator, $value)
* @method static QueryBuilder whereMonth($column, $operator, $value)
* @method static QueryBuilder whereYear($column, $operator, $value)
*/
abstract class BaseModel extends Model
{
}
Then my own models extends this model:
然后我自己的模型扩展了这个模型:
<?php
namespace Modules\Shop\Entities;
use App\BaseModel;
class MyEntity extends BaseModel
And then everything works. The BaseModel is now not complete, feel free to add further static methods, I add them on demand.
然后一切正常。BaseModel 现在还没有完成,可以随意添加更多的静态方法,我按需添加。
回答by xrayin
I found a solution that worked and was simple after having tried the _ide_help.php
solution of Barry.
Laracast video showing the solution: https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/15-- Down in the first comment you can find Barry's links.
在尝试了_ide_help.php
Barry的解决方案后,我找到了一个有效且简单的解决方案。显示解决方案的 Laracast 视频:https://laracasts.com/series/how-to-be-awesome-in-phpstorm/episodes/15
-- 在第一条评论中,您可以找到 Barry 的链接。
After having added this it did not work for me but I am still mentioning it for the sake of completion.
添加它后它对我不起作用,但为了完成,我仍然提到它。
Then I tried this:
然后我尝试了这个:
In my Model I added use Eloquent;
at the top. (I added the Eloquent by way of auto completion instead of typing).
在我的模型中,我use Eloquent;
在顶部添加。(我通过自动完成而不是键入的方式添加了 Eloquent)。
Then above my class I typed "/** hit ENTER" which automatically generated PHP Docs
in the newly generated PHP Docs I added @mixin Eloquent
down below.
然后在我的课程上方输入“/** hit ENTER”,它会在我@mixin Eloquent
在下面添加的新生成的 PHP 文档中自动生成 PHP 文档。
As a final step I hit Ctrl+Alt+Y(default settings) which is synchronize (File->Synchronize) in PhpStorm.
作为最后一步,我点击了Ctrl+ Alt+ Y(默认设置),它是 PhpStorm 中的同步(文件->同步)。
This fixed the warnings and my ::find method in my Controller was found and Auto completion was working.
这修复了警告,并在我的控制器中找到了我的 ::find 方法并且自动完成正在工作。
Down below my Class as an example:
下面以我的班级为例:
namespace App;
use Illuminate\Database\Eloquent\Model; <br>
use Eloquent;
/**
* Class Student
* @package App
* @mixin Eloquent
*/
class Student extends Model <br>
{
}
回答by MH.Kashizadeh
You can add @mixin QueryBuilder
into phpdoc of Model
Class
您可以添加@mixin QueryBuilder
到Model
类的phpdoc
File path : project_path\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php
文件路径 : project_path\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Model.php
回答by ??c chung nguy?n
I have solved this way.
我是这样解决的。
There is greate IDE support for Laravel shipped from Baryvdh:
Baryvdh 提供了对 Laravel 的强大 IDE 支持:
https://github.com/barryvdh/laravel-ide-helper
https://github.com/barryvdh/laravel-ide-helper
after you install it you just call in the console:
安装后,您只需在控制台中调用:
php artisan ide-helper:generate
which generate alll facede shortcuts in _ide_helper.php file (which you have to exclude from git)
在 _ide_helper.php 文件中生成所有 facede 快捷方式(您必须从 git 中排除)
There is also something special for PhpStorm:
PhpStorm 还有一些特别之处:
php artisan ide-helper:meta
回答by Dylan Buth
Just so this question can be "answered", you need the laravel ide-helper. Follow these instructionsand everything should work for you.
为了可以“回答”这个问题,您需要 laravel ide-helper。按照这些说明进行操作,一切都应该适合您。