【问题标题】:Laravel Query Builder joining with aliasLaravel Query Builder 加入别名
【发布时间】:2020-09-01 04:36:44
【问题描述】:

我有两张桌子

未知表

id | parent_id 

客户表

id | parent_id  

我的代码:

$transaction = DB::table($name.'_transactions')
                    ->where('user_id', $id)
                    ->join('users', 'users.id' , '=' , 'parent_id')
                    ->get();

加入将与clients.id => unknown.parent_id... 因为客户表有一个parent_id 这就是为什么我必须使用别名

请帮我这样做!

【问题讨论】:

  • 这个 $name.'_transactions' 是什么?是桌子吗?如果是表,客户表的外键是什么?
  • 是的!它是一个动态的表格。关系将是clients.id => unknown.parent_id
  • 你试过了吗:->join('clients', 'clients.id' , '=' , $name.'parent_id')
  • 是的!不工作可能不得不使用别名
  • 确实有效!顺便说一句,我错过了一些东西,谢谢

标签: sql laravel alias laravel-6


【解决方案1】:

使用别名工作解决方案:

$tablename = Roles::where('id', '=' , 6)->first();
                    $name = str_replace(' ', '_', trim($tablename->name));
                    $tb = $name.'_transactions';
                    $exist_in_db = DB::table($tb)
                                        ->where('user_id', $id)
                                        ->get();
                    if(count($exist_in_db) > 0) {
                        $transaction = DB::table("$tb as newtable")
                                        ->where('user_id', $id)
                                        ->join('users', 'users.id' , '=' , 'newtable.parent_id')
                                        ->get();

【讨论】:

    猜你喜欢
    • 2013-03-19
    • 1970-01-01
    • 2021-08-20
    • 2015-12-03
    • 2019-08-11
    • 2021-08-28
    • 2022-01-20
    • 2018-11-07
    • 2015-06-15
    相关资源
    最近更新 更多