我有hasMany
用户的项目,而belongsTo
用户的项目。
我想计算一个项目的用户总数,所以我需要链接他们。
这样我就收到了Call to undefined method Illuminate\Database\Query\Builder::user()
错误。
我究竟做错了什么?
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'));
}
}
模型
user
:public function project(){
return $this->belongsTo('App\Project', 'project_id','id');
}
模型
project
:public function users() {
return $this->hasMany('App\User', 'id');
}
HTML/ Blade :
@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
最佳答案
您必须提供定义关系的方法名称。我的意思是用户而不是用户
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'));
}
关于php - Laravel 5调用未定义的方法Illuminate\Database\Query\Builder::method(),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/30325169/