Laravel converting DB query to eloquent - php

I'm new to laravel and have been pondering with this issue for a short while now. The main reason that I'd like to use eloquent is so that the datetime stamps work as the DB method ignores the created_at and updated_at fields. I am trying to reproduce the following query to eloquent:
$user_results = DB::table('users')->
leftJoin('roles', 'users.role_id','=', 'roles.id')->
get();
I have the following database setup
user migration
<?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');
}
}
roles migration
<?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');
}
}
and the user model contains
public function role() {
return $this->belongsTo('App\Role');
}
Any help would be much appreciated.
thanks.

Simply you can replace DB::table('users') with App\User
App\User::leftJoin('roles', 'users.role_id','=', 'roles.id')->get();

Related

Laravel Migrate not creating all table

I want to create all of the tables. But Amount table was not created while migrating. is my problem right or wrong? Or why I am fetching this kind of error. here is my all migration code is
**user **
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Year_month
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class YearMonth extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('year_months',function(Blueprint $table){
$table->unsignedBigInteger('id');
$table->foreign('id')->references('id')->on('users')->onDelete('cascade');
$table->date('ym_id')->primary();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('year_months');
}
}
Meal Storage
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class MealStorage extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('meal_storages', function (Blueprint $table) {
$table->unsignedBigInteger('id');
$table->foreign('id')->references('id')->on('users')->onDelete('cascade');
$table->date('ym_id');
$table->foreign('ym_id')->references('ym_id')->on('year_months')->onDelete('cascade');
$table->unsignedBigInteger('member_id');
$table->foreign('member_id')->references('member_id')->on('members')->onDelete('cascade');
$table->date('date');
$table->integer('meal');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('meal_storages');
}
}
Member
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class MealStorage extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('meal_storages', function (Blueprint $table) {
$table->unsignedBigInteger('id');
$table->foreign('id')->references('id')->on('users')->onDelete('cascade');
$table->date('ym_id');
$table->foreign('ym_id')->references('ym_id')->on('year_months')->onDelete('cascade');
$table->unsignedBigInteger('member_id');
$table->foreign('member_id')->references('member_id')->on('members')->onDelete('cascade');
$table->date('date');
$table->integer('meal');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('meal_storages');
}
}
amount
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Amount extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('amounts',function(Blueprint $table){
$table->unsignedBigInteger('id');
$table->foreign('id')->references('id')->on('users')->onDelete('cascade');
$table->unsignedBigInteger('member_id');
$table->foreign('member_id')->references('member_id')->on('members')->onDelete('cascade');
$table->integer('amount');
$table->date('date');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('amounts');
}
}
*is that my process right or wrong *
when I migrate I am fetching this problem
enter image description here
Hey you got this error because you try to run member migration twice
check your migration if you have tow migration for this table try ro delete one or if you using a library check maby the have same migration too

SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (Laravel)

I keep getting this error. I understood it's a problem with the foreign key but i really can't understand what it's not working properly. I'm trying to make a many to many relationship with a bridge table. Please, if you can help me solve this! Here you can see the migrations:
Table dresses:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Dress extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('dresses', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('dress_id');
$table->string('name')->unique();
$table->string('brand');
$table->decimal('price');
$table->string('fabric');
$table->string('size');
$table->string('type');
$table->string('wash_instruction');
$table->string('product_details');
$table->string('fit');
$table->rememberToken();;
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
Table Wishlist:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Wishlist extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('wishlists', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('wishlist_id');
$table->foreign('wishlist_id')
->references('user_id')
->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
Bridge table:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateWishlistDressTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('wishlist_dress', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('dress_id');
$table->foreign('dress_id')
->references('id')
->on('dresses')->onDelete('cascade');
$table->unsignedBigInteger('wishlist_id');
$table->foreign('wishlist_id')
->references('id')
->on('wishlists')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('wishlist_dress');
}
}
How is your users migration set up? Do you have a column named users_id in the users migration file?
Usually, only the id column is used, which is generated from $table->id() in the users migrations file. I believe your migrations should work if you change from users_id to id like following:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Wishlist extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('wishlists', function (Blueprint $table) {
$table->id();
$table->unsignedBigInteger('wishlist_id');
$table->foreign('wishlist_id')
->references('id') //Changed from user_id to id
->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}

Inner Join-Laravel

I have three tables in my database. User, Employer and Jobs.
Some Users are Employers who have posted some jobs.
I am trying to display jobs by users.
My code:
User Model
public function jobs(){
return $this->hasManyThrough('App\Employer','App\Job');
}
Routes:
Route::get('/find_user_jobs',function(){
$user=User::find(1);
foreach($user->jobs as $job){
echo $job->created_at."<br>";
}
});
But I get this error
Column not found: 1054 Unknown column 'jobs.user_id' in 'field list' (SQL: select `employers`.*, `jobs`.`user_id` from `employers` inner join `jobs` on `jobs`.`id` = `employers`.`job_id` where `jobs`.`user_id` = 1)
I get that its trying to find user_id in jobs but here is what I want it to do
My desire for the program
When I give the user id, go to employers table search for user_id, if it exists ,go to jobs table and search for the employers_id and return all the jobs with the employer_id.
User Migration
<?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');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->integer('employer_id');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
Job migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateJobsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('jobs', function (Blueprint $table) {
$table->increments('id');
$table->integer('employer_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('jobs');
}
}
Employer Migration
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateEmployersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('employers', function (Blueprint $table) {
$table->increments('id');
$table->string('company_name');
$table->integer('user_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('employers');
}
}
The relationship arguments are in the wrong order:
public function jobs(){
return $this->hasManyThrough('App\Job', 'App\Employer');
}
Because Employee are User who have Jobs you can create a model App\Employee which extends the App\User Model
class Job {
public function employee()
{
return $this->belongsTo(App\Employee::class,'user_id');
}
}
and Create an Employee class like this
Here in the Employee Model I set the $table property to users, when we make some query that query will have the target table set to users instead of the employees table which would be the default behavior of Eloquent.
class Employee extends User
{
protected $table = "users";
public function jobs()
{
return $this->hasMany(Job::class, 'user_id');
}
}
You can use directly the Employee Model and get jobs
And here are the corresponding migration
the create_user_table
class CreateUsersTable extends Migration
{
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->string('company_name')->nullable();
$table->rememberToken();
$table->timestamps();
});
}
public function down()
{
Schema::drop('users');
}
}
The create_job_table
class CreateJobsTable extends Migration
{
public function up()
{
Schema::create('jobs', function (Blueprint $table) {
$table->increments('id');
$table->integer("user_id")->unsigned();
$table->foreign('user_id')->references('id')->on('users');
$table->timestamps();
});
}
public function down()
{
Schema::drop('jobs');
}
}

Laravel 5 - Add column and foreign key to an existing table with data

I am very new at Laravel! But I'm trying. Here is were I could use some help;
I have a posts table. I have a user table. But I forgot to add a foreign key in the posts table that links to the user id.
The create users table migration:
use Illuminate\Support\Facades\Schema;
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');
$table->string('name');
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
The create posts table migration:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreatePostsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->string('title');
$table->text('body');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('posts');
}
}
I have created the new migration file:
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterTablePostsAddForeignUser extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('posts', function (Blueprint $table) {
// I HAVE NO IDEA WHAT TO DO NEXT
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
I have no idea how to fill up the "public function up()" method here! If anyone can help! It will be much appreciated!
I tried this and this worked for me.
Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->nullable()->unsigned();
$table->foreign('user_id')->references('id')->on('users');
});
Here When you adding foreign key, by default it will have a Null value.This 'null referencing' may cause the issue. Using nullable() foreign key will avoid that issue.
See the docs here
You need to install doctraine/dbal before modifying a column, be sure to add the doctrine/dbal dependency to your composer.json file. The Doctrine DBAL library is used to determine the current state of the column and create the SQL queries needed to make the specified adjustments to the column and the you should try what I found on this SO post
Schema::table('posts', function (Blueprint $table) {
$table->integer('user_id')->unsigned()->change();
$table->foreign('user_id')->references('id')->on('users');
});
change() method for change structure of column
after this run the artisan command
php artisan migrate
if this doesn't work for you shoot the comment here! :)

Laravel 4 - one migrations in workbench can be rolled back, while others cannot

I have two types of workbench migrations: creating regular tables and creating pivot tables for Many-to-Many relationships.
Sample of regular migration:
<?php
use Illuminate\Database\Migrations\Migration;
class CreateUsersTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('users', function(\Illuminate\Database\Schema\Blueprint $table)
{
$table->increments('id')->unsigned();
$table->string('login')->unique();
$table->string('username')->unique();
$table->string('password');
$table->string('email');
$table->boolean('active')->default(true);
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Above migration can be rolled back
<?php
use Illuminate\Database\Migrations\Migration;
class CreatePivotRoleUser extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('role_user', function(\Illuminate\Database\Schema\Blueprint $table)
{
$table->integer('role_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->primary(['role_id', 'user_id']);
$table->foreign('role_id')->references('id')->on('roles')->onDelete('cascade');
$table->foreign('user_id')->references('id')->on('users')->onDelete('cascade');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('role_user');
}
}
While this cannot, because it gives
"Class 'CreatePivotPermissionRole' not found"
error.
How to fix it?
Your code looks correct.
If CreatePivotPermissionRole is not found, it means it had been deleted before. Check the content of all your down() methods, there must be something wrong there.

Categories