加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 大数据 > 正文

php – Laravel关系计数()

发布时间:2020-12-14 19:39:31 所属栏目:大数据 来源:网络整理
导读:我希望得到一个有关系的总用户事务(特定用户). 我已经做到了,但我很好奇,我的方式是好方法. //User Modelpublic function Transaction(){ return $this-hasMany(Transaction::class);}//Merchant Modelpublic function Transaction(){ return $this-hasMany(
我希望得到一个有关系的总用户事务(特定用户).
我已经做到了,但我很好奇,我的方式是好方法.

//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();

令我好奇的是countTransaction中的部分内容.我把where(‘user_id’,Request :: get(‘user_id’))直接放在模型中.

是获得特定方式的好方法还是其他任何方式?

预期结果:

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

我需要获取特定用户的交易计数的商家数据.此查询基于登录用户.因此,当用户访问商家页面时,他们可以看到该商家的交易计数.

谢谢.

解决方法

您确实希望将请求数据保留在模型之外(而不是选择将其传入).我也有点困惑为什么你有两个’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);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读