加入ON和laravel eloquent查询构建器

时间:2017-02-14 15:00:22

标签: mysql laravel eloquent

我正在尝试在laravel中编写以下sql查询:

    select 
    `workers`.`first_name`, 
    `workers`.`last_name`, 
    `occupations`.`approval_date`, 
    `occupations`.`certification_date`, 
    `occupations`.`expiration_date`, 
    `occupations`.`type`, 
    `workers`.`photo` 

    from `worker_print_queue` 
    inner join `workers` on `worker_print_queue`.`worker_id` = `workers`.`id` 
    inner join `occupations` on `worker_print_queue`.`certification` = `occupations`.`type` AND `workers`.`id` = `occupations`.`worker_id`

我用以下方式雄辩地写出来:

$records = \DB::table('worker_print_queue')
                ->join('workers', 'worker_print_queue.worker_id', '=', 'workers.id')
                ->join('occupations', function($join){
                    $join->on('workers.id', '=', 'occupations.worker_id')
                            ->where('worker_print_queue.certification', '=', 'occupations.type');
                })
                ->select('workers.first_name', 'workers.last_name', 'occupations.approval_date',
                        'occupations.certification_date', 'occupations.expiration_date', 'occupations.type', 'workers.photo')
                ->get();

但我没有收到任何结果。我确信有些东西我不见了,只是不确定它是什么。

1 个答案:

答案 0 :(得分:1)

问题是这一行

'worker_print_queue.certification'

将列'occupations.type'与值on进行比较。

如果你改变它以使用->on('worker_print_queue.certification', '=', 'occupations.type'); 条款你应该没问题:

using System;
using SQLitePCL.pretty;
using System.Text.RegularExpressions;

namespace TestSqlite
{ 
    class Program
    {
        static void Main(string[] args)
        {
            Func<ISQLiteValue, ISQLiteValue, ISQLiteValue> regexFunc =
                        (ISQLiteValue val, ISQLiteValue regexStr) =>
                        {
                            if (Regex.IsMatch(Convert.ToString(val), Convert.ToString(regexStr)))
                                return true.ToSQLiteValue();
                            return false.ToSQLiteValue();
                        };
            SQLitePCL.Batteries.Init();
            SQLiteDatabaseConnection _dbcon = SQLiteDatabaseConnectionBuilder
                        .InMemory
                        .WithScalarFunc("REGEXP", regexFunc)
                        .Build();
            string sql = "CREATE TABLE foo (a int, b text);";
            _dbcon.ExecuteAll(sql);
            _dbcon.ExecuteAll(@"INSERT INTO foo VALUES (1, 'this is me');
                                INSERT INTO foo VALUES (2, 'that is me');
                                INSERT INTO foo VALUES (3, 'he is me');");
            sql = "SELECT * FROM foo where '\\w{4} is me' REGEXP b;";
            foreach (var row in _dbcon.Query(sql)) { Console.WriteLine(row[1].ToString()); }
        }
    }
}