我有hasMany
个用户和用户belongsTo
项目的项目。
我想计算一个项目的用户总数,所以我需要将它们链接起来。
这样我收到Call to undefined method Illuminate\Database\Query\Builder::user()
错误。
我做错了什么?
控制器:
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 /刀片:
@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
答案 0 :(得分:3)
您必须提供定义关系的方法名称。我的意思是用户不是用户
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'));
}