I have one table named Content which is a master table like
Content : id content_name created_at updated_at
and another table Course like
Course table have many content_id
Course : id content_id course_name created_at updated_at
I have created relation like this.
Content Model
class Content extends Eloquent {
protected $table = 'contents';
protected $guarded = array('id');
public function course()
{
return $this->belongsTo('Course');
}
}
Course Model
class Course extends Eloquent {
protected $table = 'courses';
protected $guarded = array('id');
public function content()
{
return $this->hasMany('Content');
}
}
When i am fething the data like this
$courses=Course::find(1)->content;
It throws error like
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'contents.course_id' in 'where clause' (SQL: select * from contents where contents.course_id = 1)
I am unable to rectify the problem in relations as I am new to laravel.
Close, but you have your relationships backwards. The table that has the foreign key is the one that belongsTo the other one. In this case, your course table has the foreign key content_id, therefore Course belongs to Content, and Content has one or many Courses.
class Content extends Eloquent {
public function course() {
return $this->hasMany('Course');
}
}
class Course extends Eloquent {
public function content() {
return $this->belongsTo('Content');
}
}
in your migrations(create_courses_table) , make sure to set the foreign key like that ,
$table->integer('content_id)->unsigned()->index();
$table->foreign('content_id')
->references('id')
->on('contents')
->onDelete('cascade');
I don't really understand your table design, maybe it should be something like this.
Taking your statement: "Course table have many content_id". I perceive that you are saying that 1 course can have multiple content, is that right? If yes, you might want to change your table design to something like below
Course
======
id
course_name
created_at
updated_at
Content
=======
id
course_id (set this as FK)
content_name
created_at
updated_at
migration code for content
public function up()
{
Schema::create('content', function(Blueprint $table)
{
$table->engine = 'InnoDB';
$table->increments('id');
$table->integer('course_id')->unsigned();
$table->string('content_name');
});
Schema::table('content',function($table)
{
$table->foreign('course_id')->references('id')->on('course')->onDelete('cascade');
});
}
Then in your model
class Course extends Eloquent
{
protected $table = 'course';
public function content()
{
return $this->hasMany('content', 'course_id', 'id');
}
}
class Content extends Eloquent
{
protected $table = 'content';
public function course()
{
return $this->belongsTo('course', 'course_id', 'id');
}
}
Then to access your data via eager loading
$course = Course::with('content')->get();
OR
$content = Content::with('course')->get();
This is about determining associations. Your associations should be:
Content
Content has many courses
class Content extends Eloquent {
protected $table = 'contents';
protected $guarded = array('id');
public function courses()
{
return $this->hasMany('Course');
}
}
Course
The course belongs to content.
class Course extends Eloquent {
protected $table = 'courses';
protected $guarded = array('id');
public function content()
{
return $this->belongsTo('Content');
}
}
So you can do query association.
For finding content -> courses:
$courses = Content::find(1)->courses;
For finding course -> content:
$content = Course::find(1)->content;
Related
In my application, there will be multiple investors tagged for single purchase entry. So on loading a purchase entry, I should get all the investors associated.
In my controller,
return response()->json(GoldPurchase::with('investors')->get());
Mapping table schema,
Schema::create('gold_purchase_investor', function (Blueprint $table) {
$table->increments('id');
$table->integer('investor_id')->unsigned();
$table->integer('purchase_id')->unsigned();
$table->timestamps();
$table->foreign('investor_id')
->references('id')
->on('investors')
->onDelete('cascade');
$table->foreign('purchase_id')
->references('id')
->on('gold_purchases')
->onDelete('cascade');
});
Purchase model,
class GoldPurchase extends Model
{
public function investors() {
return $this->hasMany('App\GoldPurchaseInvestor');
}
}
Investor model,
class Investor extends Model
{
protected $fillable = ['name', 'address', 'mobile', 'email'];
public function purchases() {
return $this->hasMany('App\GoldPurchase');
}
}
PurchaseInvestor model,
class GoldPurchaseInvestor extends Model
{
protected $table = 'gold_purchase_investor';
public function purchase() {
return $this->belongsTo('App\GoldPurchase');
}
public function investor() {
return $this->belongsTo('App\Investor');
}
}
With this, I am getting error,
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'gold_purchase_investor.gold_purchase_id' in 'where clause' (SQL: select * from `gold_purchase_investor` where `gold_purchase_investor`.`gold_purchase_id` in (1))
You have to specify the custom foreign key:
public function investors() {
return $this->hasMany('App\GoldPurchaseInvestor', 'purchase_id');
}
But this is actually a case for a BelongsToMany relationship:
public function investors() {
return $this->belongsToMany('App\Investor', 'gold_purchase_investor', 'purchase_id');
}
From the Eloquent Relationship:
Remember, Eloquent will automatically determine the proper foreign key column on the Comment model. By convention, Eloquent will take the "snake case" name of the owning model and suffix it with _id. So, for this example, Eloquent will assume the foreign key on the Comment model is post_id.
$this->hasMany('App\Comment', 'foreign_key', 'local_key');
So try to write your foreign key and local key in the relationships
In your case I think it would be something like that:
class GoldPurchase extends Model`
{
public function investors() {
return $this->hasMany('App\GoldPurchaseInvestor', 'investor_id', 'id');
}
}
Use belongsToMany for many-to-many relationships.
GoldPurchase.php
class GoldPurchase extends Model{
public function investors() {
return $this->belongsToMany('App\Investor','gold_purchase_investor','purchase_id','investor_id');
}
}
Investor.php
class Investor extends Model{
protected $fillable = ['name', 'address', 'mobile', 'email'];
public function purchases() {
return $this->belongsToMany('App\GoldPurchase','gold_purchase_investor','investor_id','purchase_id');
}
}
You don't need a third model for pivot table at all.
GoldPurchaseInvestor is not at all needed.
I would like to get many "badges" to one "company"
I have 3 tables companies, badgy, badgy_company as pivot table.
What should I try/do? Can someone give me a hint or something?
company.blade.php
#foreach($listings->badgy as $type)
<span class="label label-default">{!! $type->title !!}</span>
#endforeach
Badgy.php
class Badgy extends Model{
protected $table = 'badgy';
public function badgy()
{
return $this->hasMany(Company::class);
}
If I remove protected $table = 'badgy'; I get error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'MYDATABASE.badgies' doesn't exist
Company.php
public function badgy()
{
return $this->belongsToMany(Badgy::class);
}
In page controllers I try:
$listings = Company::find($id);
$listings = Company::query()->get();
If I need to provide any more info, please, just ask.
You are not following the Laravel naming conventions. As a result, the default values used for relations by the framework don't work. You will have to set them manually as follows:
class Badgy
{
protected $table = 'badgy'; // Laravel default would be 'badgies'
public function companies()
{
return $this->belongsToMany(Company::class, 'badgy_company', 'category_id', 'company_id');
}
}
class Company
{
protected $table = 'companies'; // optional as the default is the same
public function badgies()
{
return $this->belongsToMany(Badgy::class, 'badgy_company', 'company_id', 'category_id');
}
}
Please also have a look at another answer of mine where I explain some important pieces regarding relationships and naming conventions. Because in a perfect scenario you would have the following tables and columns:
companies:
- id
- name
badgies:
- id
- title
badgy_company:
- id
- badgy_id
- company_id
Which would allow your models to look like this:
class Badgy
{
public function companies()
{
return $this->belongsToMany(Company::class);
}
}
class Company
{
public function badgies()
{
return $this->belongsToMany(Badgy::class);
}
}
I'm trying to create a league table in Laravel but I'm running into some issues with guess what, relationships, again. They never seem to work for me in Laravel. It's like they hate me.
I have a modal for matches
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class Match extends Model
{
protected $primaryKey = 'id';
protected $table = 'matches';
public $timestamps = false;
protected $guarded = ['id'];
}
And a modal for teams, but with a matches() function
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $primaryKey = 'id';
protected $table = 'teams';
public $timestamps = false;
protected $guarded = ['id'];
public function matches() {
return $this->hasMany('App\Database\Match', 'team_one_id, team_two_id');
}
}
I think the issue comes with team_one_id, team_two_id as the teams primary key could be in either one of them columns for the other table. When calling count() on matches() it throws an error.
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'matches.team_one_id, team_two_id' in 'where clause' (SQL: select count(*) as aggregate from matches where matches.team_one_id, team_two_id = 1 and matches.team_one_id, team_two_id is not null)
can you try this syntax
return $this->hasMany('modelPath', 'foreign_key', 'local_key');
Does Match table have a column maned 'team_id'?
because it's the default naming convention in the laravel docs for mapping the tables.
if you do have the column and populate the data you can just remove the foreign & local keys from matches() relationship. you don't need it. Laravel will automatically map it for you.
if you do not have the 'team_id' on Matches table please add the column and add the respective team ids for matches.
<?php
namespace App\Database;
use Illuminate\Database\Eloquent\Model;
class Team extends Model
{
protected $primaryKey = 'id';
protected $table = 'teams';
public $timestamps = false;
protected $guarded = ['id'];
public function matches() {
return $this->hasMany('App\Database\Match');
}
}
This way you can implement it, Add these relationship and a method in Team Model
public function homeMatches() {
return $this->hasMany('App\Database\Match', 'team_one_id');
}
public function awayMatches() {
return $this->hasMany('App\Database\Match', 'team_two_id');
}
public function matches() {
return $this->homeMatches->merge($this->awayMatches);
}
Now Fetch the data
$team = Team::find(1);
$matches = $team->matches(); //now it will fetch all matches for both columns
If you want to fetch matches as attributes then you can add one method
in your Team model
public function getMatchesAttribute()
{
return $this->homeMatches->merge($this->awayMatches);
}
Now you can fetch the matches as $matches = $team->matches;
Here is the difference
$team->matches returns Illuminate\Database\Eloquent\Collection
And
$team->matches() returns Illuminate\Database\Eloquent\Relations\{Relation Name}
You can't use matches in Eager loading like Team::with('matches') because matches is not a relationship and that causing your Error. What you can do is add homeMatches and awayMatches in eager loading and then call $team->matches().
$teams = Team::with('homeMatches', 'awayMatches')->get();
$teams->each(function ($team) {
print_r($team);
print_r($team->matches());
});
I'm trying to do browser game like Tribal Wars in Laravel.
I want to get building level by using $wioska->buildings->Tartak->level, but something not working:
This is my Building model:
class Building extends Model
{
protected $table = 'budynki';
public function Tartak(){
return $this->hasOne('App\Tartak');
}
}
Wioska (village) model:
class Wioska extends Model
{
protected $fillable = ['name', 'user_id'];
protected $table = 'wioski';
public function user(){
return $this->belongsTo('App\User');
}
public function buildings(){
return $this->hasOne('App\Building');
}
}
And this is my Tartak model:
class Tartak extends Model
{
protected $table = 'budynki';
public function level(){
$u = Auth::user();
$id = $u->wioska->id;
return DB::table('budynki')->where('wioska_id', $id)->first();
}
}
Migration "budynki":
public function up()
{
if(!Schema::hasTable('budynki')) {
Schema::create('budynki', function (Blueprint $table) {
$table->integer('town_hall')->default(1);
$table->integer('iron')->default(0);
$table->integer('wood')->default(0);
$table->integer('stone')->default(0);
$table->integer('bread')->default(0);
$table->integer('wioska_id');
$table->foreign('wioska_id')->references('id')->on('wioski');
});
}
}
1) It's always good to check for a null entity before trying to call its methods. Example, if $wioska->buildings is null or wioska has no buildings, or buildings have no Tartak, then the rest of the line will throw errors.
2) level() is a method and since its not an authentic Laravel relationship, you will need to use it as a method, example - $wioska->buildings->Tartak->level()
level is not property as per your model, so you have to try as below
$wioska->buildings->Tartak->level()
Now I've got
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'budynki.building_id' in 'where clause' (SQL: select * from budynki where budynki.building_id is null and budynki.building_id is not null limit 1) error
I just want to get tartak level from budynki table: https://i.imgur.com/zoTx5tE.png .
There is something I miss in the eloquent one-to-one relationship:
class MeetingTest extends Model
{
protected $table = 'meeting_tests';
public function meeting() {
return $this->belongsTo('App\Meeting','meeting_id','id');
}
public function observation() {
return $this->hasOne('App\Observation','meeting_test_id','id');
}
public function activity() {
return $this->hasOne('App\TestActivity','activity_id','id');
}
}
The Observation Class is
class Observation extends Model
{
protected $table = 'observations';
public function meetingTest() {
return $this->belongsTo('App\MeetingTest','meeting_test_id','id');
}
}
If I run php artisan tinker and
$mtn = App\MeetingTest::create();
$mtn->save();
$ob = App\Observation::create();
$ob->save;
$mtn->observation()->save($ob);
At this point inside the Observation record I can see the meeting_test_id filled with the correct id of the meetingTest, but if I try:
$mtn->observation
it gives me null; and in the Database there is no observation ID in the observation_id field;
this is the migration:
Schema::create('meeting_tests', function (Blueprint $table) {
$table->increments('id');
$table->integer('meeting_id')->unsigned();
$table->integer('observation_id')->unsigned()->nullable();
$table->integer('activity_id')->unsigned()->nullable();
$table->timestamps();
});
I don't understand what is not correct.
I can see observation_id and activity_id in your meeting_tests table, which makes records in this table the owned side of one-to-one/one-to-many relation. Therefore, both activity and observation relations in MeetingTest should return $this->belongsTo instead of $this->hasOne