Number of Laravel () Relations

I want to get a general user transaction (specific user) with relationships. I did this, but I'm curious that my approach is a good approach.

//User Model
public function Transaction()
{
    return $this->hasMany(Transaction::class);
}

//Merchant Model

public function Transaction()
{
    return $this->hasMany(Transaction::class);
}

public function countTransaction()
{
    return $this->hasOne(Transaction::class)
        ->where('user_id', Request::get('user_id'))
        ->groupBy('merchant_id');
}

public function getCountTransactionAttribute()
{
    if ($this->relationLoaded('countTransaction'))
        $this->load('countTransaction');

    $related = $this->getRelation('countTransaction');

    return ($related) ? (int)$related->total_transaction : 0;
}

//controller

$merchant = Merchant::with('countTransaction')->get();

What I'm curious about is the part inside countTransaction. I put where where('user_id', Request::get('user_id'))directly inside the model.

is this a good approach or any other way to get a specific way?

Expected Result:

"merchant:"{
    "name": "example"
    "username" : "example"
    "transactions": {
        "count_transactions: "4" //4 came from a specific user.
    }
}

I need to get merchant data with a transaction account for a specific user. This request is based on a registered user. therefore, when the access page is useraccess, they can see their transaction number for this merchant.

Thanks.

+4
source share
1

( ). , "hasOne" , "hasMany" .

, , , (, ). , , , ,

    // Merchant Model
    public function transactions()
    {
        return $this->hasMany(Transaction::class);
    }

    public function countTransactionsByUser($userId)
    {
        return $this
                ->transactions()
                ->where('user_id', $userId)
                ->get()
                ->pluck('total_transaction')
                ->sum();
    }

    // Controller

    $userId = request()->get('user_id');

    // ::all() or however you want to reduce 
    // down the Merchant collection
    //
    $merchants = Merchant::all()->map(function($item, $key) {
        $_item = $item->getAttributes();
        $_item['transactions'] = [
            'count_transactions' => $item->countTransactionsByUser($userId);
        ];
        return $_item;
    });

    // Single total
    // Find merchant 2, and then get the total transactions 
    // for user 2
    //
    $singleTotal = Merchant::find(2)
        ->countTransactionsByUser($userId); 
+1

Source: https://habr.com/ru/post/1622677/


All Articles