Laravel 5.4需要通过雄辩的关系获得不同的记录

use*_*429 4 php mysql distinct-values laravel-eloquent laravel-5.4

我有一个表"交易".在该表中,我有多个列,分别是id,user_id,customer_name,restaurant_name和时间戳.我需要的是,如果表中有两个或三个相同的记录,则表示restaurant_name正在重复使用相同的user_id.我只需要获得独特的记录.如果用户从同一家餐厅订购3次,我只需要从那里购买1份.

示例: 如果我订购必胜客3次,并从地铁订购5次.结果应该包含1个披萨小屋和1个地铁.

注意: 1个用户可能有很多交易

交易模型:

<?php

namespace App;
use App\restaurant;
use App\User;

use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
    public function user(){
        return $this->belongsTo(User::class);
    }

    public function restaurant(){
        return $this->belongsTo(restaurant::class);
    }

    protected $fillable = [
        'user_id','customer_name', 'restaurant_name' , 'ordered_items' , 
    ];
}
Run Code Online (Sandbox Code Playgroud)

用户模型:

<?php

namespace App;
use App\restaurant;
use App\User;

use Illuminate\Database\Eloquent\Model;

class Transaction extends Model
{
    public function user(){
        return $this->belongsTo(User::class);
    }

    public function restaurant(){
        return $this->belongsTo(restaurant::class);
    }

    protected $fillable = [
        'user_id','customer_name', 'restaurant_name' , 'ordered_items' , 
    ];
}
Run Code Online (Sandbox Code Playgroud)

我试图得到这样的预期结果,但它显示我的错误:

BadMethodCallException in Macroable.php line 74:
Method distinct does not exist.

$user->transactions->distinct("restaurant_name");
Run Code Online (Sandbox Code Playgroud)

Jer*_*dev 10

distinct不是Laravel集合的现有功能,但是unique.

$user->transactions->unique("restaurant_name");
Run Code Online (Sandbox Code Playgroud)

但是,这将查询所有事务并过滤代码.要使用查询获取不同的行,您可以执行以下操作:

$user->transactions()->groupBy('restaurant_name')->get();
Run Code Online (Sandbox Code Playgroud)