2016-07-31 101 views
2

我是laravel的新手,一直在思考这个问题。我想使用雄辩的主要原因是,日期时间戳记的工作原理是DB方法忽略created_at和updated_at字段。我试图复制下面的查询,以雄辩:Laravel将DB查询转换为雄辩

$user_results = DB::table('users')-> 
        leftJoin('roles', 'users.role_id','=', 'roles.id')-> 
        get(); 

我有以下的数据库设置

用户迁移

<?php 

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class CreateUsersTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('users', function (Blueprint $table) { 
      $table->increments('id')->unsigned(); 
      $table->integer('role_id')->unsigned()->index(); 
      $table->string('name'); 
      $table->string('email')->unique(); 
      $table->string('password'); 
      $table->rememberToken(); 
      $table->timestamps(); 
     }); 
    } 

    /** 
    * Reverse the migrations. 
    * 
    * @return void 
    */ 
    public function down() 
    { 
     Schema::drop('users'); 
    } 
} 

角色迁移

<?php 

use Illuminate\Database\Schema\Blueprint; 
use Illuminate\Database\Migrations\Migration; 

class CreateRolesTable extends Migration 
{ 
    /** 
    * Run the migrations. 
    * 
    * @return void 
    */ 
    public function up() 
    { 
     Schema::create('roles', function (Blueprint $table) { 
      $table->increments('id'); 
      $table->string('rolename'); 
      $table->timestamps(); 
     }); 
    } 

    /** 
    * Reverse the migrations. 
    * 
    * @return void 
    */ 
    public function down() 
    { 
     Schema::drop('roles'); 
    } 
} 

和用户模型包含

public function role() { 
    return $this->belongsTo('App\Role'); 
} 

任何帮助将不胜感激。

谢谢。

回答

0

简单,你可以使用App \用户

应用程序\用户:: leftJoin( '角色', 'users.role_id', '=',“roles.id取代DB ::表( '用户') ') - > get();

+0

这正是我正在寻找,但无法弄清楚。谢谢zillion。 –