I am trying to get some relational data. All the methods work well but only one method is not working. I am trying to call App\ModeltestMcqQuestion::find(id)->chapterwiseMcqs from tinker, but it is returning null. My database is well populated. I have tried with many id, but nothing is working.
My Models are:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ChapterwiseMcq extends Model
{
use SoftDeletes;
protected $fillable = [
'topic_id',
'question_type',
'question',
'question_description',
'question_resource',
'a',
'b',
'c',
'd',
'answer',
'answer_description',
'answer_resource',
];
public function topic(){
return $this->belongsTo(Topic::class);
}
public function modeltestMcqAnswers(){
return $this->hasMany(ModeltestMcqAnswer::class);
}
public function modeltestMcqQuestions(){
return $this->hasMany(ModeltestMcqQuestion::class);
}
}
Another Model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
class ModeltestMcqQuestion extends Model
{
use SoftDeletes;
protected $fillable = [
'modeltest_question_set_id',
'chapterwise_mcq_id',
];
public function modeltestQuestionSet(){
return $this->belongsTo(ModeltestQuestionSet::class);
}
public function chapterwiseMcqs(){
return $this->belongsTo(ChapterwiseMcq::class);
}
}
Migrations:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateChapterwiseMCQSTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('chapterwise_mcqs', function (Blueprint $table) {
$table->id();
$table->foreignId('topic_id')->constrained()->onDelete('cascade')->onUpdate('cascade');
$table->integer('question_type');
$table->string('question');
$table->text('question_description')->nullable();
$table->string('question_resource')->nullable();
$table->string('a');
$table->string('b');
$table->string('c');
$table->string('d');
$table->string('answer');
$table->text('answer_description')->nullable();
$table->string('answer_resource')->nullable();
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('chapterwise_m_c_q_s');
}
}
Another migration:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateModeltestMcqQuestionsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('modeltest_mcq_questions', function (Blueprint $table) {
$table->id();
$table->foreignId('modeltest_question_set_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->foreignId('chapterwise_mcq_id')->constrained()->onUpdate('cascade')->onDelete('cascade');
$table->timestamps();
$table->softDeletes();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('modeltest_mcq_questions');
}
}
All the relational queries work well except App\ModeltestMcqQuestion::find(id)->chapterwiseMcqs. Can anyone help me what is wrong with the code? Here, id represents id of the model.
I have found a solution. Defining the funtion name caused the problem, I think.
public function chapterwiseMcqs()
Thu function name should be chapterwiseMcq(), not chapterwiseMcqs(). Changing the name worked for me.
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
I'm working on team management project.
I have a problem with doing relationships.
I want to display users in boards, but also want to look good and easy to read. I already designed relationships but when I saw JSON output of relationships, it was completely messed.
Is there some way how to display relationship data this way?
{
"id": 1,
"name: "Test",
"members": [
{
... user model here
"name": "Peter",
"email": "peter#peter.com",
}
]
}
My migrations:
Boards migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateBoardsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('boards', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('boards');
}
}
Membership migration
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMembershipsTable extends Migration
{
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('memberships', function (Blueprint $table) {
$table->increments('id');
$table->integer('board_id')->unsigned();
$table->integer('user_id')->unsigned();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::dropIfExists('memberships');
}
}
EDIT:
Models
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Board extends Model
{
protected $fillable = ['name'];
public function members() {
return $this->hasMany(Membership::class)->with('user');
}
}
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Membership extends Model
{
protected $fillable = ['board_id', 'user_id'];
protected $hidden = ['created_at', 'updated_at'];
public function user() {
return $this->hasOne(User::class, 'id', 'user_id');
}
}
You can try to define the relationships in the models as a Many to Many one, i.e.:
class User
{
public function boards()
{
return $this->belongsToMany('App\Board', 'memberships', 'user_id', 'board_id');
}
}
class Board
{
public function members()
{
return $this->belongsToMany('App\User', 'memberships', 'board_id', 'user_id');
}
}
With that relations defined you don't really need a Membership Model if it has not additional fields, and you can write code like that:
User::find($id)->boards
Board::find($id)->members
Board::with('members')->find($id)
You could read also the documentation on Many to Many Relationships
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'm trying to make Laravel ORM working and it keeps inserting empty records in database. The ID created_at and updated_at are correctly inserted but the values are not. Here are the files:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class TesterTest extends Model
{
protected $fillable = ['name','value'];
public $name;
public $value;
}
The migration file:
<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateTestTable extends Migration {
/**
* Run the migrations.
*
* #return void
*/
public function up()
{
Schema::create('my_tests', function (Blueprint $table) {
$table->increments('id');
$table->string('name');
$table->integer('value');
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* #return void
*/
public function down()
{
Schema::drop('my_tests');
} }
And this is how Im calling it:
$flight = new TesterTest;
$flight->name = "Tester1";
$flight->save();
There is a something Im missing but can't figure it out.
I would say that adding in public $name; and public $value; in your model is causing problems. Try removing those two lines.