嗨,我正在尝试从我的客户端控制器查询三个表,我的数据库的快速概览,users
clients
projects
tasks
user
hasMany
clients
,projects
和tasks
,这些projects
和tasks
也belongTo
client
。
所以我在客户端控制器中,我想查询登录的users
clients
projects
,但是当我尝试这样做时,我被抛出一个未定义的方法错误:
BadMethodCallException Call to undefined method Illuminate'Database'Query'Builder::user()
不确定为什么会发生这种情况,我单独查询了客户端项目,它工作正常,但是当我添加额外的层时,它会给我抛出上述错误。
我是 Laravel 4 的新手,因此希望得到一些指导来帮助纠正错误并帮助我了解我出错的地方。
我的代码如下:
客户端控制器.php
public function show($id)
{
$client = Client::find($id);
$client->load(array('projects' => function($query)
{
// With the clients for each project
$query->with('user');
}));
// Create an empty array
$associated = array();
// Loop through client projects
foreach($client->projects as $project):
// Loop through project users
foreach($project->user as $user):
// Check if the user is the same as the logged in user
if($user->id == Auth::user()->id){
// If yes add the $project to the $associated array
array_push($associated, $project);
}
endforeach;
endforeach;
// show the view
return View::make('clients.show')
->with('client', $client);
}
客户端/显示刀片.php
<?php $clients = $client->projects; ?>
@if (Auth::check())
@if (count($clients) > 0)
@foreach ($clients as $project)
<div class="one-third column">
<div class="projects">
<ul class="data">
<li><label>Project Name: </label><a class="btn btn-small btn-success" href="{{ URL::to('project/' . $project->id.'/show' ) }}"> {{ $project->project_name }}</a></li>
<li><label class="titletoggle">Project Brief <p>(click to toggle)</p></label><p class="brief">{{ $project->project_brief }}</p></li>
</ul>
<ul class='buttonslist'>
<li><button><a href="{{ URL::to('project/' . $project->id . '/edit') }}">Edit Project</a></button></li>
<li><button><a href="/task/create">Create Task</a></button></li>
<li><button><a href="/task/view/">View Tasks</a></button></li>
</ul>
</div>
</div>
@endforeach
@else
<h3>You have no projects click <a href="/project/create">here to create a project</a></h3>
@endif
@endif
问题与您急切加载的方式有关。特别是这部分。
$client->load(array('projects' => function($query)
{
// With the clients for each project
$query->with('user');
}));
急切加载这些嵌套关系的正确方法是。
$client->load(array(
'projects',
'projects.user',
));
或者更简单地说。
$client->load('projects.user');
或者,您可以在初始查询期间设置预先加载。
$client = Client::with('projects.user')->find($id);
你也没有提到项目属于用户。需要在项目模型中定义此关系。
class Project extends Eloquent {
public function user()
{
return $this->belongsTo('User');
}
}
缺少此方法可能是错误消息的原因。Eloquent 会将对未定义方法的调用转发到其内部查询生成器对象。查询生成器对象没有 user() 方法,因此这就是您收到该错误的原因。