6

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");
user8499429
  • 67
  • 1
  • 1
  • 6
  • Your `User` model has no relation to `Transaction`? I have a feeling you miss copied your code because there are two `Transaction` classes. – Jerodev Aug 22 '17 at 09:37
  • Sorry about that. User model have this function ... – user8499429 Aug 22 '17 at 09:39
  • class User extends Authenticatable { use Notifiable; public function transactions(){ return $this->hasMany(Transaction::class); } } – user8499429 Aug 22 '17 at 09:39

1 Answers1

17

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();
Jerodev
  • 32,252
  • 11
  • 87
  • 108