[英]Laravel 5.4 need to get distinct records through eloquent relation
我有一個表“交易”。 在該表中,我有多個列,分別是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' ,
];
}
用戶模型:
<?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' ,
];
}
我試圖得到這樣的預期結果,但它顯示我的錯誤:
BadMethodCallException in Macroable.php line 74:
Method distinct does not exist.
$user->transactions->distinct("restaurant_name");
distinct
不是Laravel集合的現有功能,但unique
是。
$user->transactions->unique("restaurant_name");
但是,這將查詢所有事務並過濾代碼。 要使用查詢獲取不同的行,您可以執行以下操作:
$user->transactions()->groupBy('restaurant_name')->get();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.