I am working on a project where, I have been assigned a task to create user management for the application. But I have stuck on the table relationship and their migration.
Effort
I have these tables:
Users
user_id
username
password
Profiles
profile_id
user_id
firstname
lastname
email
Address
address_id
profile_id
address
city
state
country
pincode
Configurations
config_id
configuration_name
configuration_type
parent_id
Now I have to create model and migration for the same above structure. For this i have create/modify below model and migration class.
Model: User
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'username', 'password',
];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function profile()
{
return $this->hasOne('Profile','user_id');
}
}
Migration: 2014_10_12_000000_create_users_table.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('user_id');
$table->string('username');
$table->string('password', 60);
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('users');
}
}
Model: Profile
use Illuminate\Database\Eloquent\Model;
class Profile extends Model
{
public function user(){
return $this->belongsTo('User');
}
public function address()
{
return $this->hasOne('Address','address_id');
}
}
Migration: 2016_02_26_101749_create_profiles_table.php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateProfilesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('profiles', function (Blueprint $table) {
$table->increments('profile_id');
$table->integer('user_id')->unsigned();
$table->foreign('user_id')->references('user_id')->on('users')->onDelete('cascade');
$table->string('lastname')->nullable();
$table->string('firstname')->nullable();
$table->string('gender')->nullable();
$table->string('email')->unique();
$table->string('phonenumber', 20)->nullable();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('profiles');
}
}
Model: Addess
namespace App;
use Illuminate\Database\Eloquent\Model;
class Address extends Model
{
public function profile(){
return $this->belongsTo('Profile');
}
public function city() {
return $this->hasOne('Configuration', 'config_id');
}
public function state() {
return $this->hasOne('Configuration', 'config_id');
}
public function country() {
return $this->hasOne('Configuration', 'config_id');
}
}
Migration: 2016_02_26_102805_create_addresses_table.php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateAddressesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('addresses', function (Blueprint $table) {
$table->increments('address_id');
$table->integer('profile_id')->unsigned();
$table->foreign('profile_id')->references('profile_id')->on('profiles')->onDelete('cascade');
$table->string('address')->nullable();
$table->integer('city')->unsigned();
$table->foreign('city')->references('config_id')->on('configurations')->onDelete('cascade');
$table->string('pincode')->nullable();
$table->integer('state')->unsigned();
$table->foreign('state')->references('config_id')->on('configurations')->onDelete('cascade');
$table->integer('country')->unsigned();
$table->foreign('country')->references('config_id')->on('configurations')->onDelete('cascade');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('addresses');
}
}
Model: Configuration
namespace App;
use Illuminate\Database\Eloquent\Model;
class Configuration extends Model
{
public function children() {
return $this->hasMany('Configuration','parent_id');
}
public function parent() {
return $this->belongsTo('Configuration','parent_id');
}
public function address(){
return $this->belongsTo('Address');
}
}
Migration: 2016_02_26_104519_create_configurations_table.php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateConfigurationsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('configurations', function (Blueprint $table) {
$table->increments('config_id');
$table->string('configuration_name');
$table->string('configuration_type');
$table->string('parent_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('configurations');
}
}
Now, when I run php artisan migrate I am getting error that :
.
Please suggest me how to do that. I have to use same table structure and cannot modify it. If any further update require or I forgot something please let me know.
That happen because migration will try to migrate address table before configuration so it will not found the foreign key config_id you're referenced, so you could change the name of migrations files then the migration commad could pass the configurations_table migrate file first then the addresses_table migrate file, so just change :
2016_02_26_104519_create_configurations_table.php
To :
2016_02_26_102005_create_configurations_table.php
_____________^
After that you should run optimize command to regenerating optimized class loader :
php artisan o
And rerun php artisan migrate command now the problem should be solved.
Hope this helps.
Related
I have a problem while attempting to seed my pivot table in database in Laravel. I get error
Base table or view not found: 1146 Table 'user_cuisines' doesn't exist
And my table name is actually user_cuisine, so it is like for some reason laravel doesn't show that table. I added in my relationships that user_cuisine is pivot table because of alphabet order. Any help is appreciated. Here is my code.
UserCuisineTableSeeder.php
<?php
use App\UserCuisine;
use App\UserProfile;
use Illuminate\Database\Seeder;
class UserCuisineTableSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
$cuisines = UserCuisine::all();
UserProfile::all()->each(function ($userProfile) use ($cuisines) {
$userProfile->cuisines()->attach(
$cuisines->random(rand(1, 12))->pluck('id')->toArray()
);
});
}
}
DatabaseSeeder.php
<?php
use Illuminate\Database\Seeder;
class DatabaseSeeder extends Seeder
{
/**
* Seed the application's database.
*
* #return void
*/
public function run()
{
$this->call(WhitelabelTableSeeder::class);
$this->call(CitiesTableSeeder::class);
$this->call(UserTableSeeder::class);
$this->call(UserProfilePropertiesSeeder::class);
$this->call(UserProfileTableSeeder::class);
$this->call(FieldTableSeeder::class);
$this->call(FieldValueTableSeeder::class);
$this->call(CuisineTableSeeder::class);
$this->call(LiteratureTableSeeder::class);
$this->call(MusicTableSeeder::class);
$this->call(SportTableSeeder::class);
$this->call(TvTableSeeder::class);
$this->call(UserCuisineTableSeeder::class);
$this->call(UserInterestTableSeeder::class);
}
}
UserCuisine.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCuisine extends Model
{
protected $fillable = [
'name'
];
public function userProfiles()
{
return $this->belongsToMany(UserProfile::class, 'user_cuisine');
}
}
UserProfile.php
<?php
namespace App;
class UserProfile
{
public function user()
{
return $this->belongsTo(User::class);
}
public function cuisines()
{
return $this->belongsToMany(UserCuisine::class, 'user_cuisine');
}
}
user_cuisine_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUserCuisineTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('user_cuisine', function (Blueprint $table) {
$table->bigIncrements('id');
$table->unsignedBigInteger('user_id');
$table->unsignedBigInteger('cuisine_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('user_cuisine');
}
}
cuisine_table
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateCuisineTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('cuisine', function (Blueprint $table) {
$table->bigIncrements('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('cuisine');
}
}
Laravel expect the table name to be user_cuisines but you named it user_cuisine without the "s"
You can fix that by changing your migration or adding protected $table = 'user_cuisine'; to your model.
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class UserCuisine extends Model
{
protected $table = 'user_cuisine';
}
As naming convention goes, I would recommend changing the table name 👍
Seems user_cuisines table does not exist, You have created cuisine not user_cuisines
Just put below code in UserCuisine model.
protected $table= 'user_cuisine';
I would recommend always use -m flag while creating a model to avoid these types of errors, for example.
php artisan make:model ModelName -m
This is my first time posting here, sorry if i input something incorrectly.
So i have Forums.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Forums extends Model
{
protected $table ='forums';
public $primaryKey='id';
public function section()
{
return $this->belongsTo(Section::class,'id');
}
}
and Section.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Section extends Model
{
public function forums()
{
return $this->hasmany(Forums::class,'section_id');
}
}
I fallowed tutorial in which it was shown that using
$section=Section::find($id)->forums;
i should get all the forums that had fk equal to section $id, however ir returns empty array.
I tried to output sql in terminal using:
$order = App\Section::find(2)->forums()->toSql()
where 2 is sections table id and got:
select * from `forums` where `forums`.`section_id` is null and `forums`.`section_id` is not
null"
so no wonder it returns empty array
however if i try to get section related to forum it works perfectly.
How could i fix this?
Changing hasmady to hasMany didn't fix it
<?php
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('Forums', function (Blueprint $table) {
$table->increments('id');
$table->string('Name');
$table->string('Description');
$table->integer('topics');
$table->integer('Comments');
$table->integer('Last_Post_id');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('Forums');
}
}
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AddToUsers extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::table('Forums', function (Blueprint $table)
{
$table->integer('Section_id');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
can't seem to find sections shema though i have it's table in database or is because that shema isn't in project folder, because im not getting errors that table or col can't be found?
I am struggling to see, where I went wrong. It seams easy, I followed Laravel instructions https://laravel.com/docs/5.4/eloquent-relationships#has-many-through , but clearly I need someone more familar with this sort of code as whenever I try to fetch $stagingsystem-stagesubtype I get error
BadMethodCallException with message 'Call to undefined method >Illuminate\Database\Query\Builder::hasManyTrough()'
Can someone help?
StagingSystems
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStagingSystemsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('staging_systems', function (Blueprint $table) {
$table->increments('id');
$table->string('name')->unique();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('staging_systems');
}
}
StageName
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStageNamesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stage_names', function (Blueprint $table) {
$table->increments('id');
$table->integer('staging_system_id')->unsigned();
$table->foreign('staging_system_id')->references('id')->on('staging_systems');
$table->string('name')->unique;
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('stage_names');
}
}
StageSubType
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateStageSubTypesTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('stage_sub_types', function (Blueprint $table) {
$table->increments('id');
$table->integer('stage_name_id')->unsigned();
$table->foreign('stage_name_id')->references('id')->on('stage_names');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('stage_sub_types');
}
}
MODELS
StagingSystem
<?php
namespace App;
use App\StagingSystem;
use Illuminate\Database\Eloquent\Model;
class StagingSystem extends Model
{
protected $guarded = ['id'];
public function stagename()
{
return $this->hasMany('App\StageName');
}
public function stagesubtype()
{
return $this->hasManyTrough('App\StageSubType','App\StageName');
}
}
StageName
<?php
namespace App;
use App\StageName;
use Illuminate\Database\Eloquent\Model;
class StageName extends Model
{
protected $guarded = ['id'];
public function stagingsystem()
{
return $this->belongsTo('App\StagingSystem','id');
}
public function stagesubtype()
{
return $this->hasMany('App\StageSubType');
}
}
StageSubType
<?php
namespace App;
use App\StageSubType;
use Illuminate\Database\Eloquent\Model;
class StageSubType extends Model
{
protected $guarded = [
'id'
];
public function stagename()
{
return $this->belongsTo('App\StageName');
}
public function stagingsystem()
{
return $this->belongsTo('App\StagingSystem');
}
}
For anyone coming across this with a similar issue, this error message can appear if you are trying to access a models relationship using withPivot(), but the intermediate relationship extends Model instead of Pivot.
You have mistyped HasManyThrough as hasManyTrough.
I have created a file Order.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
/**
* The table associated with the model.
* #var string
*/
protected $table = 'order';
}
Then I have created a migration, called 2016_01_01_111111_create_orders_table.php:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateOrdersTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('order', function (Blueprint $table) {
$table->increments('id');
$table->string('orderIdent');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
Then I did the migration with
php artisan migrate
Then, I wanted to add some fields, created a new migration file called 2016_01_02_111111_alter_orders.php:
<?php
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class AlterOrders extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
//
Schema::table('order', function(Blueprint $table)
{
$table->string('selecteddate');
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
//
}
}
Then again I did
php artisan migrate
But now I get this message in console:
[Illuminate\Database\QueryException]
SQLSTATE[42S01]: Base table or view already exists: 1050 Table 'order' already exists
What do I need to do, to add the new fields to my table?
Thanks in advance!
Adding this as an answer vs a comment to show what needs to be done. Since rollback was done, up needs to be commented out for now.
public function up()
{ /*
Schema::create('order', function (Blueprint $table) {
$table->increments('id');
$table->string('orderIdent');
$table->timestamps();
}); */
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('order');
}
Try this
public function up()
{
//
Schema::table('order', function($table)
{
$table->string('selecteddate');
});
}
remove Blueprint.
Try this :
php artisan migrate:refresh
I have the following:
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateFinanceAccountsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('finance_accounts', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('created_by')->index();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('finance_accounts');
}
}
And the seeder:
class FinanceAccountsTableSeeder extends Seeder
{
public function run()
{
DB::table('finance_accounts')->delete();
App\Models\Finance\FinanceAccount::create([
'name' => 'Default account',
'created_by' => 1
]);
}
}
Which is called via:
class DatabaseSeeder extends Seeder
{
/**
* Run the database seeds.
*
* #return void
*/
public function run()
{
Model::unguard();
$this->call('UserRolesTableSeeder');
$this->call('UserTableSeeder');
$this->call('FinanceTransactionsTableSeeder');
$this->call('FinanceAccountsTableSeeder');
$this->call('CurrencyTableSeeder');
$this->call('UserProfileTableSeeder');
}
}
However, the table is created fine, but no data gets inserted.
The seeders for all my other tables work perfectly, just not for this one.
Does anyone have an idea why?
namespace App\Models\Finance;
use Illuminate\Database\Eloquent\Model;
class FinanceAccount extends Model {
protected $table = 'finance_accounts';
}