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. 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. I need to get only unique records. If user ordered from same restaurant 3 times I need to get only 1 from those.
Example: If I order form Pizza Hut 3 time and ordered from Subway 5 times. The result should contain 1 pizza hut and 1 subway.
Note: 1 user may have many transactions
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.
$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();