2013-07-24 58 views
1

我有一個小問題;Laravel 4查詢顯示

我在我的數據庫中有兩張表:第一張是'賬戶',第二張是'玩家'。我已經完成了與模型的關係,我已經完成了所有工作。但是,有些事我沒有做過。

在'accounts'表中有一個名爲'id'的列。在'players'表中有一個名爲'account_id'的列,它與'accounts'表中的'id'相匹配。

我想顯示讓我們說玩家的名字(位於「玩家」表中的列名'')。我怎麼能顯示,比如說,當一個人登錄('賬戶'表)時,顯示玩家的名字('玩家'表中列'名'),但與相匹配的ID?

例如: 'accounts' id = 1; name = 12345 'players' id = 1;名字=約翰; account_id = 1;

現在,當我登錄ID爲1的帳戶('accounts'table)時,我希望它顯示所有擁有account_id = 1的玩家。我也想讓它與所有帳戶/ ID一起使用,而不只是一個帳戶。

我已經嘗試做這樣的事情:

 public function player() 
{ 
    $player = Player::find(3); 
    return View::make('aac.test')->with('player',$player); 
} 

這只是一個球員的3號,沒什麼配合ACCOUNT_ID,它只是顯示爲3

的ID玩家

而且,這裏是我的user.php的(模型;用於 '賬戶')和Player.php(模型;用於 '玩家')

user.php的

<?php 

use Illuminate\Auth\UserInterface; 
use Illuminate\Auth\Reminders\RemindableInterface; 

class User extends Eloquent implements UserInterface, RemindableInterface { 

    /** 
    * The database table used by the model. 
    * 
    * @var string 
    */ 
    protected $table = 'accounts'; 


    /** 
    * 
    * 
    * Timestamps: true if needed, otherwise false. 
    * 
    */ 
    public $timestamps = false; 

    /** 
    * The attributes excluded from the model's JSON form. 
    * 
    * @var array 
    */ 
    protected $hidden = array('password'); 

    /** 
    * Get the unique identifier for the user. 
    * 
    * @return mixed 
    */ 
    public function getAuthIdentifier() 
    { 
     return $this->getKey(); 
    } 

    /** 
    * Get the password for the user. 
    * 
    * @return string 
    */ 
    public function getAuthPassword() 
    { 
     return $this->password; 
    } 

    /** 
    * Get the e-mail address where password reminders are sent. 
    * 
    * @return string 
    */ 
    public function getReminderEmail() 
    { 
     return $this->email; 
    } 

    public function players() { 
     return $this->hasMany('Player'); 
    } 

} 

Player.php

<?php 

class Player extends Eloquent { 


    protected $table = 'players'; 

    protected $fillable = array('char_name', 'sex'); 
    public $timestamps = false; 

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

回答

2

只要得到你所需要的帳戶,您將有機會獲得玩家收集。然後,您只需在您的視圖中遍歷account->players即可。

public function players() 
{ 
$account = User::find(1); 
return View::make('aac.test')->with('account',$account); 
} 

在你看來,你可以通過玩家遍歷

<?php foreach($account->palyers as $player):?> 
    <?php echo $player->name;?> 
<?php endforeach;?> 

希望這有助於

+0

它實際上有很大幫助。這裏是我得到的錯誤: 異常 SQLSTATE [42S22]:未找到列:1054'where子句'中的未知列'players.user_id'(SQL:select * from'players'其中'players'.'user_id' in (?,?))(綁定:數組(0 => 1,1 => 15,)) – dinomuharemagic

+0

你的關係和用戶模型是如此的按照慣例,它試圖找到'user_id'而不是'account_id'。嘗試在關係'return $ this-> belongsTo('User','account_id');' – Altrim

+0

'中添加您的自定義鍵值對不起'在'Player'模型中反過來'return $ this-> hasMany('Player 」, 'ACCOUNT_ID')'。 – Altrim