Laravel ManyToMany为同一型号

Okay guys, i am trying to rephrase my question. Lets see how try 2 goes :)

I have a artisan command to calculate the total earnings for every user.

Every day a User gets earnings assigned. But sometime, how should I describe it, he made the earnings with stuff from another user.

And thats the assert_user_id column. If a user (user 2) made earnings with stuff from another user (user 1), these earnings should be added to the earnings of user 1 in this scenario.

id, user_id, earnings, asset_user_id
 1,   1,        15,       null
 2,   1,        43,       null
 3,   1,        49,       null
 4,   2,        32,       1
 5,   2,        25,       1
 6,   2,        12,       null

(In this case, user 2 is making almost all of his money with content from user 1... not very nice of him, thats why the money)

The Artisan commands gets all users. and goes through them with a foreach.

inside the foreach we call a method on the user model

return $this->sum('earnings');

remember, I am inside the collection of user 1.

And now I want to sum all earnings where asset_user_id = 1. The problem, the collection persist only the rows of user 1.

Now the question:

How can i access all other rows from inside a collection of a user. Yeha i could just do User:all() within my function in my model. But i don't think this would be SOLID code. So how do i do it the right way?

What you will probably want to do is iterate over the collection with foreach and get the sums yourself.

$results = Result::all();

$sum1 = 0;
$sum2 = 0;

foreach($results as $result) {
    if($result->creator_id == 1 && $result->status = 'r') {
        $sum1 += (int)$result->earnings;
    }

    if($result->asset_creator_id == 1 && $result->status = 'r') {
        $sum2 += (int)$result->earnings;
    }
}

There is also a sum method in the Collection class which might be a bit easier. Just send it a callback which returns the value you are looking for. We would have to do it twice though, once for each sum you are looking for.

$sum1 = $results->sum(function($result)
{
    if($result->creator_id == '1' && $result->status = 'r') {
        return $result->earnings;
    }
});

$sum2 = $results->sum(function($result)
{
    if($result->asset_creator_id == '1' && $result->status = 'r') {
        return $result->earnings;
    }
});

echo "Creator Earnings: ".$sum1;
echo "Asset Creator Earnings: ".$sum2;

Sorting, counting, summing over collection would be always worse solution than doing it with db query.

Anyway your question is messy, you ask for status=r, write total for status=f, so just a guess, to show you how you can accomplish that with Eloquent features:

public function getEarningsForAssetCreator($id)
{
  return $this->where('asset_creator_id', $id)
           ->where('status', 'f')
           ->sum('earnings');
}