2013-11-15 60 views
0
時侃侃而談未定義的方法用戶

你好我想查詢從我的客戶端控制器三個表,我的數據庫的快速概覽,usersclientsprojectstasks一個userhasManyclientsprojectstasks這些projectstasksbelongTo a clientLaravel查詢3個表

所以我在客戶機控制器,我想查詢登錄usersclientsprojects,但是當我嘗試這樣做我拋出一個未定義的方法錯誤:

BadMethodCallException Call to undefined method Illuminate\Database\Query\Builder::user()

我m不知道爲什麼會發生這種情況,我單獨查詢客戶端項目並且它工作正常,但是當我添加一個附加層時,它會引發上述錯誤。

我是Laravel 4的新手,所以希望能得到一些幫助糾正錯誤的指導,並幫助我瞭解哪裏出錯。

我的代碼如下:

ClientController.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); 

    } 

客戶/ show.blade.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 

回答

1

這個問題有做的方式,您都渴望加載。具體是這個部分。

$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()方法,所以這就是爲什麼你會得到這個錯誤。

+0

非常感謝,工作!在將來加載時會考慮到這一點 – 001221