简体   繁体   English

如何在laravel中连接两个表?

[英]How to join two tables in laravel?

I am new to Laravel.我是 Laravel 的新手。 I am having a difficulty in joining two tables (User Table and Transaction Table).我在连接两个表(用户表和事务表)时遇到困难。 Below are codes from TransactionController.下面是来自 TransactionController 的代码。

public function index()
{
    $user = User::all();
    $transactions = $user->transactions;
    $transaction = array();

    foreach ($transactions as $row) {
        array_push($transaction,
        [
            'id' => $row->id,
            'name' => $row->user->name,
        ]
        );
    }

    return response() -> json ([
        'transaction' => $transaction,
    ]);
}

I would like to print all users' name and all transactions in the Postman.我想打印邮递员中的所有用户名和所有交易。 I manage to print all users' name but when I tried to join with Transaction table, I am facing an error.我设法打印了所有用户的姓名,但是当我尝试加入交易表时,我遇到了错误。 I already tried left join method as below:我已经尝试过左连接方法如下:

$user = User::all() 
  ->select('user.id','user.name')
  ->join('transactions','transactions.id','=','user.id')
  ->get();

  foreach ($transactions as $row) {
        array_push($transaction,
        [
            'id' => $row->id,
            'name' => $row->user->name,
        ]
        );
    }

    return response() -> json ([
        'transaction' => $transaction,
    ]);
}

Is there any way to join two tables in laravel?有没有办法在laravel中连接两个表? Thank you.谢谢你。

Assuming you have this relationship in your User model.假设您的 User 模型中有这种关系。

public function transactions() {
  return $this->hasMany('App\Transaction', 'user_id');
}

And in your Transaction model在你的交易模型中

public function user() {
  return $this->belongsTo('App\User', 'user_id');
}

Now, to fetch users together with their transactions现在,将用户与其交易一起获取

$users = User::with('transactions')->get();

If you want to fetch transactions inline with user如果您想获取与用户内联的交易

 $data = Transaction::with('user')->get();

 $transactions = collect($data)->map(function ($transaction){
    return [
        'id' => $transaction->id,
        'name' => $transaction->user->name,
        'total' => $transaction->total,
    ];
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM