首页 文章

Laravel - Eloquent加入

提问于
浏览
2

我刚开始学习laravel及其orm系统,Eloquent . 我不知道如何正确地连接表格 . 我有3个模型:用户,帐户,帐户类型,我不知道如何使用帐户类型加入帐户 .

帐户模型类:

public function accounttype(){
    return $this->hasOne('AccountType');
}

这是为了传递帐户信息来查看:

$accounts = User::find(Auth::user()->id)->accounts;
$accounts->load('accounttype');
return View::make('accounts.accounts')->with('accounts', $accounts);

这将产生以下错误:

SQLSTATE [42S22]:找不到列:1054未知列'accounttypes.account_id' in 'where clause'(SQL:select * from accounttypes where accounttypes . account_id in(1,2,3))

它应该通过帐户类型表中的id而不是account_id来提取 . 我可以很好地列出用户帐户,我只是不知道如何将帐户类型表加入帐户表 .

数据库表:

用户

  • id

  • 用户名

  • 密码

  • 个时间戳(updated_at / created_at)

帐号

  • id

  • 名字

  • user_id

  • accounttype_id

  • 时间戳

AccountTypes

  • id

  • 名字

每个用户可以拥有多个帐户,每个帐户都有一个帐户类型 .

1 回答

  • 3

    User 型号中:

    public function accounts()
    {
        return $this->hasMany('Account');
    }
    

    Account 型号中:

    public function user()
    {
        return $this->belongsTo('User');
    }
    
    public function accountType()
    {
        return $this->belongsTo('AccountType', 'accounttype_id', 'id');
    }
    

    AccountType 型号中:

    public function accounts()
    {
        return $this->hasMany('Account', 'accounttype_id', 'id');
    }
    

    然后在你的控制器中:

    // This will return a user with all accounts ($user->accounts will be collection)
    $user = User::with('accounts')->find(Auth::user()->id);
    

    要么:

    $user = User::with('accounts.accountType')->find(Auth::user()->id);
    
    // You may pass the $user as well and then loop the $user->accounts in view
    return View::make('accounts.accounts')->with('accounts', $user->accounts);
    

    在您的 view 中,您可以循环获取所有帐户,例如:

    @foreach($accounts as $account)
        {{ $account->name }}
        {{ $account->accountType->name }}
    @endforeach
    

    由于 $user->accounts 是一个集合,因此您可以运行 loop 或使用以下内容专门获取帐户:

    {{ $accounts->first()->name }}; // Get first one's name
    {{ $accounts->get(0)->name }}; // Get first one's name
    {{ $accounts->get(1)->name }}; // Get second one's name
    {{ $accounts->last()->name }}; // Get last one's name
    

    如果您传递 $user 而不是 $accounts ,如下所示:

    return View::make('accounts.accounts')->with('user', $user);
    

    然后改变循环,如下所示:

    @foreach($user->accounts as $account)
        {{ $account->name }}
        {{ $account->accountType->name }}
    @endforeach
    

    在开始循环之前,您可以确保该用户是否在 view 中拥有帐户,例如:

    @if($user->accounts->count())
        // Loop Here
    @endif
    

相关问题