php Laravel 5 调用未定义的方法 Illuminate\Database\Query\Builder::method()
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30325169/
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
Laravel 5 Call to undefined method Illuminate\Database\Query\Builder::method()
提问by Liam
I have projects which hasMany
users, and users belongsTo
a project.
我有哪些hasMany
用户belongsTo
的项目,而用户有一个项目。
I want to count the total amount of users a project has so I need to link them.
我想计算一个项目的用户总数,所以我需要链接它们。
This way I'm getting a Call to undefined method Illuminate\Database\Query\Builder::user()
error.
这样我就Call to undefined method Illuminate\Database\Query\Builder::user()
出错了。
What am I doing wrong?
我究竟做错了什么?
Controller:
控制器:
class ProjectController extends Controller
{
private $project;
public function __construct(Project $project){
$this->project = $project;
// $this->project = $project
// ->with('user');
}
public function index(Project $project)
{
$projects = $project->with('user')->get();
$currenttime = Carbon::now();
// return view('project.index', array('projects' => $projects, 'currenttime' => $currenttime));
return view('user.index', compact('projects'));
}
}
}
Model user
:
型号user
:
public function project(){
return $this->belongsTo('App\Project', 'project_id','id');
}
Model project
:
型号project
:
public function users() {
return $this->hasMany('App\User', 'id');
}
HTML/Blade:
HTML/刀片:
@if(isset($projects))
<table class="table table-striped table-hover table-dynamic datatable">
<thead>
<tr>
<th>{{ trans('common.project') }}</th>
<th>{{ trans('common.workers') }}</th>
<th>{{ trans('common.completion_date') }}</th>
<th>{{ trans('common.status')}}</th>
</tr>
</thead>
<tbody>
@foreach($projects as $project)
<tr>
<td>{!! link_to_route('project.edit', $project->name, [$project->id] )!!}</td>
<td>{{ $project->id }}</td>
<td>{{ $project->completion_date }}</td>
@if (($project->completed) == 1)
<td><span class="label label-success">{{ trans('common.completed') }}</span></td>
@elseif(($project->completion_date) < $currenttime )
<td><span class="label label-danger">{{ trans('common.toolate') }}</span></td>
@elseif(($project->active) == 0)
<td><span class="label label-default">{{ trans('common.inactive') }}</span></td>
@else
<td><span class="label label-warning">{{ trans('common.inprogress') }}</span></td>
@endif
</tr>
@endforeach
</tbody>
</table>
@endif
回答by Imtiaz Pabel
You have to provide the method name that defines the relationship.I mean users not user
您必须提供定义关系的方法名称。我的意思是用户不是用户
public function index(Project $project)
{
$projects = $project->with('users')->get();
$currenttime = Carbon::now();
// return view('project.index', array('projects' => $projects, 'currenttime' => $currenttime));
return view('user.index', compact('projects'));
}