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.
public function Transaction()
{
return $this->hasMany(Transaction::class);
}
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;
}
$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.
source
share