Inner Join-Laravel - php

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');
}
}

Related

Problem with error: 1215 Cannot add foreign key constraint

How to solve this error? SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL: alter table invoices add constraint invoices_form_id_foreign foreign key (form_id) references forms (id) on delete cascade)
I get it after: php artisan migrate:fresh
For foreign keys in invoices get this error. 3 foreign keys generate error but one for user_id is good and works fine. I tried all solutions and didn't worked. Please help me.
2014_10_12_000000_create_users_table.php
<?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->increments('id');
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('surname')->nullable();
$table->string('showname')->nullable();
$table->string('business')->nullable();
$table->string('NIP')->nullable();
$table->string('PESEL')->nullable();
$table->string('address')->nullable();
$table->string('city')->nullable();
$table->string('postalcode')->nullable();
$table->string('phone')->nullable();
$table->string('comments')->nullable();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
2020_07_23_104440_invoices.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Invoices extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('invoices', function (Blueprint $table) {
$table->increments('id');
$table->string('invoicenumber')->nullable();
$table->date('invoicedate')->nullable();
$table->date('selldate')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->integer('form_id')->unsigned()->nullable();
$table->integer('currency_id')->unsigned()->nullable();
$table->integer('proform_id')->unsigned()->nullable();
$table->string('paymentmethod')->nullable();
$table->date('paymentdate')->nullable();
$table->string('status')->nullable();
$table->string('comments')->nullable();
$table->string('city')->nullable();
$table->string('paid')->nullable();
$table->string('autonumber')->nullable();
$table->string('automonth')->nullable();
$table->string('autoyear')->nullable();
$table->timestamps();
});
Schema::table('invoices', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users');
$table->foreign('form_id')
->references('id')
->on('forms');
$table->foreign('currency_id')
->references('id')
->on('currencys');
$table->foreign('proform_id')
->references('id')
->on('proforms');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('invoices');
}
}
2020_07_27_090356_proforms.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Proforms extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('proforms', function (Blueprint $table) {
$table->increments('id');
$table->string('proformnumber')->nullable();
$table->date('proformdate')->nullable();
$table->date('selldate')->nullable();
$table->integer('user_id')->unsigned()->nullable();
$table->string('paymentmethod')->nullable();
$table->date('paymentdate')->nullable();
$table->string('status')->nullable();
$table->string('comments')->nullable();
$table->timestamps();
});
Schema::table('proforms', function (Blueprint $table){
$table->foreign('user_id')
->references('id')
->on('users');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('proforms');
}
}
2020_07_28_091856_forms.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Forms extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('forms', function (Blueprint $table) {
$table->increments('id');
$table->string('form')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('forms');
}
}
2020_07_28_091919_currencys.php
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class Currencys extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('currencys', function (Blueprint $table) {
$table->increments('id');
$table->string('currency')->nullable();
$table->string('course')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('currencys');
}
}
Here is what might be happening with your migrations.
1. Check the the primary and foreign key type. If user primary key ID is type $table->increments('id'); // bigInteger, then the foreign key should be bigInteger as well $table->bigInteger('user_id');
2. Please check your migration order. For example table invoices has foreign key fromforms table. During the migration, forms table should migrate first. And to make it make it happen, just rename the migration file(numeric section of file name) so that the forms.
because when excuting the migration reach this line:
$table->foreign('form_id')->references('id')->on('forms');
in 2020_07_23_104440_invoices file
the forms table has not been created yet
you should make a new migration to make that relation
Schema::table('invoices', function (Blueprint $table){
$table->foreign('form_id')
->references('id')
->on('forms');
}
this migration should be after 2020_07_28_091856_forms.php migration ...
The problem is the order of the migration
see the order
2020_07_23_104440_invoices.php
2020_07_28_091856_forms.php
when the invoices table is created there will be no forms table as it is created afterwards. So the error is because you are trying to create relationship between non existing forms table id field while creating invoices table.
What you can do is create a new migration file for attaching the relationship only.
here is how to do it
delete add foreign key from. remove this part from 2020_07_23_104440_invoices.php
$table->foreign('form_id')
->references('id')
->on('forms');
after removing create seperate migration for adding forign key
run
php artisan make:migration add_form_foreign_key_to_invoices
It will generate the new migration file. Update it like this.
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class AddFormForeignKeyToInvoices extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('invoices', function (Blueprint $table) {
$table->foreign('form_id')->references('id')->on('forms');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::table('invoices', function (Blueprint $table) {
$table->dropForeign('form_id');
});
}
}

Trying to get property 'id' of non-object Laravel 7.X

Now I have two Models: user.php and Trx.php. I have created a one to many relationships as below:
User Model:
public function transactions()
{
return $this->hasMany('App\Trx');
}
Trx Model:
public function user()
{
return $this->belongsTo('App\User');
}
And this is the controller method for process data from Trx.php model and sending data to the views:
public function purchasedPlan()
{
$page_title = 'Purchased Plan';
$transactions = Trx::where('type', 7)->orderBy('id', 'DESC')->paginate(config('constants.table.default'));
$empty_message = 'No data found.';
// dd($transactions);
return view('admin.reports.transactions', compact('page_title', 'transactions', 'empty_message'));
}
Now the problem is that when I try accessing the data from the model, that's the $transactions, everything is working well except when I try getting the user in the relationship established like this in the blade template:
transactions.blade.php
<td> {{ $trx->user->username }}</td>
With that, I get this error:
Error:
[2020-05-24 05:35:40] production.ERROR: Trying to get property 'id' of non-object (View: /home/icashers/public_html/acc/core/resources/views/admin/reports/transactions.blade.php) {"exception":"[object] (ErrorException(code: 0): Trying to get property 'id' of non-object (View: /home/icashers/public_html/acc/core/resources/views/admin/reports/transactions.blade.php)
What am I doing wrong please? Anyone who's seeing what I am not please help. Thank you in advance😂
Trx.php Migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTrxesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('trxes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->nullable();
$table->string('amount',50)->nullable();
$table->string('main_amo',50)->nullable();
$table->string('charge',50)->nullable();
$table->string('type',50)->nullable();
$table->string('title')->nullable();
$table->string('trx')->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('trxes');
}
}
User.php Migration:
<?php
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('firstname');
$table->string('lastname');
$table->string('username')->unique();
$table->string('email')->unique();
$table->string('mobile')->unique();
$table->decimal('balance', 11, 2)->default(0);
$table->string('password');
$table->string('image')->nullable();
$table->text('address')->nullable()->comment('contains full address');
$table->tinyInteger('status')->default(1)->comment('0: banned, 1: active');
$table->tinyInteger('ev')->default(0)->comment('0: email unverified, 1: email verified');
$table->tinyInteger('sv')->default(0)->comment('0: sms unverified, 1: sms verified');
$table->string('ver_code')->nullable()->comment('stores verification code');
$table->dateTime('ver_code_send_at')->nullable()->comment('verification send time');
$table->tinyInteger('ts')->default(0)->comment('0: 2fa off, 1: 2fa on');
$table->tinyInteger('tv')->default(1)->comment('0: 2fa unverified, 1: 2fa verified');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Your migration has an error.... no foreign key defined>
public function up()
{
Schema::create('trxes', function (Blueprint $table) {
$table->bigIncrements('id');
$table->integer('user_id')->nullable();
$table->foreign('user_id')->references('id')->on('users');
$table->string('amount',50)->nullable();
$table->string('main_amo',50)->nullable();
$table->string('charge',50)->nullable();
$table->string('type',50)->nullable();
$table->string('title')->nullable();
$table->string('trx')->nullable();
$table->timestamps();
});
}

Laravel converting DB query to eloquent

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();

Laravel 5.2 Foreign Key fails

I am trying to add a foreign key in my posts table to reference the id in the users table. Here are my migrations, the users table is the default one packed with laravel so the timestamps are from NOV 2014 however the posts is one I created. Any help greatly appreciated.
Thanks a lot :)
Users migration
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->string('name')->unique();
$table->string('email')->unique();
$table->string('password');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
posts migration
<?php
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')->unsigned();
$table->string('title');
$table->string('section');
$table->string('body');
$table->date('post_created_date');
$table->integer('author_id')->unsigned()->after('id');
$table->foreign('author_id')->references('id')->on('users');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('posts');
}
}
Every time I migrate I get the following error:
If you are creating a table, you don't want to use after as it will create a syntax error. Just place the column where you want it. I believe after will only work for alter table statements.
Schema::create('posts', function (Blueprint $table) {
$table->increments('id'); // Unsigned is assumed for increments so I removed that as well
$table->integer('author_id')->unsigned();
$table->string('title');
$table->string('section');
$table->string('body');
$table->date('post_created_date');
$table->timestamps();
$table->foreign('author_id')->references('id')->on('users');
});
Then in your model, you'd setup the relationship to your users table like so...
public function author()
{
return $this->belongsTo(User::class, 'author_id');
}
Feel free to rename the function however you want, I usually prefer to name it something that matches the foreign key.
Then you'd use it like $post->author->name.
In your CreatePostsTable class, can you try this ?
public function up()
{
Schema::create('posts', function (Blueprint $table) {
$table->increments('id');
$table->integer('author_id')->unsigned();
$table->string('title');
$table->string('section');
$table->string('body');
$table->date('post_created_date');
$table->timestamps();
});
Schema::table('posts', function($table) {
$table->foreign('author_id')->references('id')->on('users');
});
}

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