【问题标题】:Laravel two references to same tableLaravel 对同一张表的两次引用
【发布时间】:2018-09-03 22:55:56
【问题描述】:

我有一个带有 sender_id 和 receiver_id 列的事务表,它们都是用户的引用。

现在,我想为用户创建一个 hasMany 关系。 (所有用户的交易,无论是接收还是发送)

【问题讨论】:

    标签: laravel relationship has-many


    【解决方案1】:

    在您的用户模型中创建发送者和接收者 hasMany 关系,并在您的事务模型中创建类似的 belongsTo

    用户.php

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

    交易

    public function sender(){
      return $this->belongsTo(User::class, 'sender_id');
    }
    
    public function receiver(){
      return $this->belongsTo(User::class, 'receiver_id');
    }
    

    【讨论】:

    • 我想要的是用户模型中的函数事务,它返回所有发送和/或接收的事务的集合。
    • 我已经更新了代码。检查这是否有效。您可以通过发送方或接收方拉取所有交易(发送或接收)
    【解决方案2】:

    您可以为所有交易创建一个关系:

    public function transactions() {
        return $this->hasMany(Transaction::class, 'sender_id')
            ->orWhere('transactions.receiver_id', $this->id);
    }
    

    但这不是一个非常优雅的解决方案,因为它会破坏急切加载。

    更好的解决方案是使用两个关系,然后将它们合并:

    public function senderTransactions() {
        return $this->hasMany(Transaction::class, 'sender_id');
    }
    
    public function receiverTransactions() {
        return $this->hasMany(Transaction::class, 'receiver_id');
    }
    
    public function getTransactionsAttribute() {
        return $this->senderTransactions->merge($this->receiverTransactions);
    }
    

    然后像这样使用它:

    $transactions = $user->transactions;
    

    【讨论】:

    • Tnx Jonas,不知道有合并功能
    • 调用senderTransactions时如何调用Sender Name, Receiver Name
    猜你喜欢
    • 1970-01-01
    • 2014-03-17
    • 2020-05-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 2020-03-24
    相关资源
    最近更新 更多