DISTINCT在laravel ELOQUENT问题上的应用。

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

在我的laravel应用程序中, 我有两个表, app和app_payments.我想把这两个表连接起来, 我在下面的laravel ELOQUENT中提到了. 在加入的表中, 我有一列用来存储用户ID (user_id). 下面的ELOQUENT给我返回了多条特定用户的记录。

$sites=DB::table('app_payments')
        ->join('apps', 'app_payments.app_id', '=', 'apps.appId')
        ->select('app_payments.*', 'apps.*')
        ->where ('apps.appId','=',$id)
        ->get();
return view('payments.show',compact('sites'))
            ->with('i', (request()->input('page', 1) - 1) * 100); 

但是我只需要为一个(特定的)用户id选择一行,我知道我可能要在那里使用DISTINCT,但是,在这个laravel ELOQUENT中使用它很困难。

我如何修改上面的ELOQUENT来实现这个目的?

php mysql laravel eloquent distinct
1个回答
1
投票

你发布的代码使用的是 查询生成器 (DB::table('app_payments')->...),而不是 雄辩 (AppPayment::where(...)->...->get())

你的目的是要从这些表中得到什么?直接用Query Builder继续做,还是用Eloquent,扩展Query Builder?

在Eloquent中,你会在查询生成器中设置 关系 模式中的应用和支付之间。

public function app()
{
  $this->belongsTo(App::class, 'appId');
}
public function user()
{
  $this->belongsTo(User::class);
}

类似于...

AppPayment::where('appId', $id)->with(['app', 'user'])->get()

会返回所有对应App和用户的Payments。

当然,当你期望每个用户只得到一个支付时,这还不能完成工作。 在我看来,这听起来你最好用其他方式查询,但这个决定取决于你实际需要什么数据。

对于 最后的 付款,这将是类似。

// App\Models\User.php
...
public function payments()
  return $this->hasMany(AppPayment::class)
    ->with(['app'])
    ->orderByDesc('created_at');
...

// query anywhere
$users = User::with(['payments', 'payment.app'])
  ->whereHas('payments', function (Builder $query) use($app_id){
    $query->where('app_id', $app_id);
  })
  ->get()

// latest payment:
foreach($users as $user){
  $latestPayment = $user->payments[0];
  ...
}

代码未经测试... 而且还需要一个技巧,只能(!)获取特定应用的最新支付,我把这一点给弄丢了......

© www.soinside.com 2019 - 2024. All rights reserved.