【问题标题】:Laravel - Join with a table with composite primary keyLaravel - 加入具有复合主键的表
【发布时间】:2014-06-07 17:44:26
【问题描述】:

我的问题是在 Laravel 框架中加入 2 个表。一是动态名称表(它是一个变量),二是复合主键。我必须使用查询生成器而不是 where()。详情请查看我的以下内容:

我有 2 张桌子:

CREATE TABLE `details` (
  `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
  `source_id` int(10) unsigned NOT NULL,
  `brand_id` int(10) DEFAULT NULL,
  PRIMARY KEY (`id`)
);
CREATE TABLE `links` (
  `source_id` int(10) unsigned NOT NULL,
  `brand_id` tinyint(3) unsigned NOT NULL DEFAULT '1',
  PRIMARY KEY (`source_id`,`brand_id`)
);

现在,我需要加入 2 个这些表,我使用以下代码:

<?php $results =  \DB::table('details')
            ->join('links', function($join)
            {
                $join->on('details.source_id', '=',  'links.source_id');
                $join->on('details.brand_id','=', 'links.brand_id');
            })
            ->get();?>

加入这些表很简单,OK。但我的问题是表名是动态的。

<?php 
$type = Input::get('type', null);
$table = $type . '_details';
$results =  \DB::table($table)
                ->join('links', function($join)
                {
                    // the following code will show errors undefined $table
                    $join->on($table . '.source_id', '=',  'links.source_id');
                    $join->on($table . '.brand_id','=', 'links.brand_id');
                })
                ->get();

?>

请帮我解决这个问题。 非常感谢!!!

【问题讨论】:

    标签: php mysql join laravel


    【解决方案1】:

    请尝试:

    <?php 
    $type = Input::get('type', null);
    $table = $type . '_details';
    $joinFunction = function($join) use ($table)
                    {
                        $join->on($table . '.source_id', '=',  'links.source_id');
                        $join->on($table . '.brand_id','=', 'links.brand_id');
                    }
    $results =  \DB::table($table)
                    ->join('links',$joinFunction )
                    ->get();
    
    ?>
    

    问题是函数没有看到其中的 $table 变量。这就是为什么您需要使用“使用”语句的原因。

    阅读更多关于anonymous functions in php here的信息

    【讨论】:

      【解决方案2】:

      您需要将变量从本地作用域导入匿名函数的作用域,方法如下:

      $results =  \DB::table($table)
                      ->join('links', function($join) use ($table)
                      {
                          $join->on($table . '.source_id', '=',  'links.source_id');
                          $join->on($table . '.brand_id','=', 'links.brand_id');
                      })
                      ->get();
      

      注意这一行:

      ->join('links', function($join) use ($table)
      

      问题是匿名函数不知道变量$table,所以你用use告诉它变量。

      你可以在docs找到它。

      【讨论】:

      • @Kame 没问题,我开始学习 PHP 时也遇到了同样的问题。 :)
      猜你喜欢
      • 2014-07-31
      • 2018-02-16
      • 2013-04-30
      • 1970-01-01
      • 1970-01-01
      • 2012-05-18
      • 2011-07-03
      • 2010-12-05
      • 2013-12-19
      相关资源
      最近更新 更多