[英]Laravel 5.4 need to get distinct records through eloquent relation
I have a table "transactions". 我有一个表“交易”。 in that table I have multiple columns which are id, user_id, customer_name, restaurant_name and time-stamps also. 在该表中,我有多个列,分别是id,user_id,customer_name,restaurant_name和时间戳。 What I need is if I have two or three same records in the table means restaurant_name is repeating with the same user_id. 我需要的是,如果表中有两个或三个相同的记录,则表示restaurant_name正在重复使用相同的user_id。 I need to get only unique records. 我只需要获得独特的记录。 If user ordered from same restaurant 3 times I need to get only 1 from those. 如果用户从同一家餐厅订购3次,我只需要从那里购买1份。
Example: If I order form Pizza Hut 3 time and ordered from Subway 5 times. 示例:如果我订购必胜客3次,并从地铁订购5次。 The result should contain 1 pizza hut and 1 subway. 结果应该包含1个披萨小屋和1个地铁。
Note: 1 user may have many transactions 注意: 1个用户可能有很多交易
Transaction Model: 交易模型:
<?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' ,
];
}
User Model: 用户模型:
<?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' ,
];
}
I am trying to getting desired results like this but It is showing me an error: 我试图得到这样的预期结果,但它显示我的错误:
BadMethodCallException in Macroable.php line 74:
Method distinct does not exist.
$user->transactions->distinct("restaurant_name");
distinct
is not an existing function for Laravel collections, but unique
is. distinct
不是Laravel集合的现有功能,但unique
是。
$user->transactions->unique("restaurant_name");
However that will query all transactions and filter in code. 但是,这将查询所有事务并过滤代码。 To get the distinct rows using a query, you could do the following: 要使用查询获取不同的行,您可以执行以下操作:
$user->transactions()->groupBy('restaurant_name')->get();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.