2013-04-16 16 views
0

我在用戶表中有用戶照片,我希望根據我發送的邀請訪問這些照片。嘗試抓取所有與我發送的所有邀請相關的用戶圖片。我有一個這樣的模型結構:Laravel 3 - 需要幫助傳遞嵌套數據

class User extends Eloquent 
{ 

public static $table = 'users'; 
public static $accessible = array('username', 'email', 'picture', 'password'); 

public function nests() 
{ 
    return $this->has_many('Nest'); 
} 

class Nest extends Eloquent 
{ 

public static $table = 'nests'; 

public function user() 
{ 
    return $this->belongs_to('User'); 
} 

class Invite extends Eloquent 
{ 

public static $table = 'invite'; 


public function nest() 
{ 
    return $this->belongs_to('Nest'); 
} 

這裏是我的遷移:

{ 
    Schema::create('users', function($table) { 
    // auto incremental id (PK) 
     $table->increments('id'); 
    // varchar 32 
     $table->string('username', 32); 
     $table->string('email', 64); 
     $table->string('picture'); 
     $table->string('password'); 
     $table->string('role'); 
    // boolean 
     $table->boolean('true'); 
    // created_at | updated_at DATETIME 
     $table->timestamps(); 
    }); 
} 

{ 
    Schema::create('nests', function($table) { 
    // auto incremental id (PK) 
     $table->increments('id'); 
    // varchar 32 
     $table->string('nestname', 128); 
     $table->text('info'); 
     $table->integer('user_id'); 
    // boolean 
     $table->boolean('active'); 
    // created_at | updated_at DATETIME 
     $table->timestamps(); 
    }); 
} 

{ 
    Schema::create('invite', function($table) { 

     $table->increments('id'); 
     $table->text('mypeeps'); 
     $table->integer('user_id'); 
     $table->integer('nest_id'); 
     $table->string('email', 128); 
     $table->timestamps(); 
    }); 
} 

這裏是我想獲得的圖片,但它不工作:

$users = DB::table('users') 
    ->join('nests', 'nests.user_id', '=', 'users.id') 
    ->join('invite', 'invite.nest_id', '=', 'nests.id') 
    ->where_nest_id($id) 
    ->get(array('users.picture', 'users.username')); 
+0

1.您實際上沒有描述您遇到的錯誤......請分享您在運行此代碼時發生的情況以及您期望發生的情況。 2.你已經清楚地閱讀了一些文檔,但爲什麼你在[Eager Loading](http://laravel.com/docs/database/eloquent#eager)之前停止了?你已經建立了關係並與我們分享,但決定不使用它們......這是爲什麼? –

+0

我想加急,因爲它效率更高。但是,從文檔,我無法弄清楚如何做這樣的嵌套連接。流利對我來說更直觀。 – Danaia

回答

0

好吧,我試圖猜測你有什麼問題,但我認爲是你的查詢是錯誤的,你只提取一個用戶,因爲我試過你的代碼,這就是發生在我身上的事情。

你說你想根據你發送的邀請來獲取用戶的圖片,所以最簡單的方法就是用邀請表加入用戶表,但是在你放入的代碼中,你的查詢是基於在一個嵌套的ID。

我改變你的查詢,以獲取第一批ID的邀請,基於巢的ID。然後,我再次查詢該進程在哪裏用邀請ID加入用戶表。

// fetch the ids of invitation 
$inviteIds = DB::table('invite') 
    ->join('nests', 'invite.nest_id', '=', 'nests.id') 
    ->where_nest_id($id) 
    ->get('invite.id'); 

// There must be a better clean solution for this, but it works 
$ids = array(); 
foreach($inviteIds as $id){ 
    $ids[] = $id->id; 
} 

// array of id of invites 
$users = DB::table('users') 
    ->join('invite', 'invite.user_id', '=', 'users.id') 
    ->where_in('invite.id', $ids) 
    ->get(array('users.picture', 'users.username')); 

// show the users 
dd($users);