Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

sahar_mkr's avatar

query relationships

Hi everyone, I have three tables named: transaction, transactionLog, provience. how can I reach the count of every proviences from transaction table just with eloquent model not with join with one query? my relationships:

transaction:

-id,

-amount

transaction_log:

-provience_id,

-transaction_id

provience:

-id,

-name

TransactionLog model

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

public function provience ()
{
    return $this->belongsTo(Provience::class);
}

Transaction model

public function transactionLog ()
{
    return $this->hasOne(TransactionLog::class);
}
0 likes
7 replies
vincent15000's avatar
$transaction->transaction_log->provience;

But you say : proviences count, so is there many proviences ? are you sure about the relationship you have defined ?

sahar_mkr's avatar

@vincent15000 thanks for the response, but I still have an error, what is your opinion about the relationships? I think that might not be wrong. every transaction has a log so every log belongsTo one transaction, and every provience hasMany logs

1 like
vincent15000's avatar

@sahar_mkr Ok so each transaction has many transaction logs and each transaction log has many proviences.

Perhaps you should try something like this.

$proviences = $transaction->withCount(['transaction_log' => function ($query) {
	$query->withCount('proviences');
}])->get();

Then you handle the $proviences variable to sum all proviences.

sahar_mkr's avatar

@vincent15000 I think every transaction has one log, for example when someone pays the his transaction's info goes to the transaction table and the log of this transaction(for example what was ip address and,...) goes to log table, isn't it?

1 like
vincent15000's avatar

@sahar_mkr You think or you are sure ? It's your application ;).

If each transaction has only one log, it's much easier to do (assuming that you have defined the right relationships in each model).

$proviences = count($transaction->transaction_log->proviences);
1 like
sahar_mkr's avatar
sahar_mkr
OP
Best Answer
Level 1

@vincent15000 thank you so much, but I found the way finally, any way if you have a better idea to my solution I'll be glad to read about it, solution is in below

$bestProviences = Transaction::transactionType('deposit')->get()- >groupBy('transactionLog.provience.provience_name')->map->count();

1 like
vincent15000's avatar

@sahar_mkr It would have been difficult to suggest you this solution because you didn't communicate these informations (transactionType, provience_name, ...). ;)

If you have solved your problem, don't forget to close the post by assigning the best answer to the answer that best helped you to solved your problem.

Please or to participate in this conversation.