Laravel口才从另一张表中获得一列

问题描述 投票:0回答:2

我对Laravel Eloquent有疑问。

我有下表

Users
    -id
    -email

Money
    -id
    -user_id
    -amount
    -total

用户有很多钱

我想使用类似$ user-> current_money之类的东西那么我想从最后一笔钱中获得总数

我需要这个,因为我想在表中显示所有用户当前的钱

@foreach($users as $user)
    <tr>
        <td>{{$user->email}}</td>
        <td>{{$user->current_money}}</td>
    </td>
@endforeach

是否有好的做法?

谢谢

laravel eloquent orm relation
2个回答
1
投票

我喜欢在Laravel Eloquent中使用追加来实现这一目标。

在您的用户模型中,添加$ appends数组。像这样

protected $appends = ['current_money'];

这将在用户模型中寻找方法getCurrentMoneyAttribute()。它应该看起来像这样。

public function getCurrentMoneyAttribute()
{

    return 0.00;

}

暗示您已经植入了用户表和资金表之间的关系。您的方法应如下所示,

public function getCurrentMoneyAttribute()
{

    return $this->money()->latest()->first()->total;

}

以及何时调用$user->current_money laravel执行查询,它将获得与该用户相关的Money的最后一行。


0
投票

您可以使用雄辩的关系和单个查询来完成此任务。使用append是一个滑坡,因为现在它会将其添加到所有用户查询中,并且随着应用程序的增长可能会引起膨胀。追加后将有2个查询,而不是单个查询。

在用户模型中,您像这样定义关系:

/**
 * Get money for a user
 */
public function money()
{
    return $this->hasMany('App\Money', 'user_id', 'id');
}

然后您可以在单个查询中以这种方式向用户查询性能:

$user = User::where('id', $id)->with(['money'])->first();

$user = User::with('money')->findOrFail($id);

或者现在您也可以急于付款,因为现在在用户模型中定义了关系。

$user = Auth::user(); // or however you are pulling the user from the DB.
$user->money->total;
© www.soinside.com 2019 - 2024. All rights reserved.