Laravel Eager Loading One to Many Relationship - php

Good day, I am having this problem where I am trying to retrieve the record from 2 tables
class Leads extends Eloquent
{
public function leademail()
{
return $this->hasMany('LeadDetailEmails');
}
}
class LeadDetailEmails extends Eloquent
{
public function lead()
{
return $this->belongsTo('Leads');
}
}
class Category extends BaseController
{
public function fetchRecord()
{
$result = Leads::with('leademail')->get();
}
}
leadDetailEmails has foreign key set in the migration file
$table->foreign('lead_id')->references('id')->on('leads')->onDelete('cascade');
I am getting this error:
"message":"SQLSTATE[42S22]: Column not found: 1054 Unknown column 'lead_detail_emails.leads_model_id' in 'where clause' (SQL: select * from `lead_detail_emails` where `lead_detail_emails`.`leads_model_id` in (1, 2, 3))"
What can I do to fix the error? also, if there will be a third table(LeadDetailContact), how can I eager loading the table?
thanks.

You should try specifying your table name for LeadDetailEmails in the following way:
class LeadDetailEmails extends Eloquent
{
protected $table = 'leadDetailEmails';
public function lead()
{
return $this->belongsTo('Leads');
}
}
And if you have more relations you want to get with eager loading you can do it this way:
$result = Leads::with('leademail', 'leadcontact')->get();

Related

SQLSTATE[42S22]: Column not found: in laravel livewire project

I am trying to sync the navigation menu with navigation type but I'm getting the error Illuminate\Database\QueryException SQLSTATE[42S22]: Column not found: 1054 Unknown column ' navigation_menu_id' in 'field list' (SQL: insert into 'navigation_menus_navigation_types' (' navigation_menu_id', 'navigation_type_id') values (1, 1))
I am not sure why navigation_menu_id is not found. I am using a custom pivot table with custom foreign key id.
*Migration.php
Schema::create('navigation_menus_navigation_types', function (Blueprint $table) {
$table->id('navigation_menus_navigation_types_id');
$table->unsignedBigInteger('navigation_menu_id');
$table->foreign('navigation_menu_id')->references('navigation_menus_id')->on('navigation_menus');
$table->unsignedBigInteger('navigation_type_id');
$table->foreign('navigation_type_id')->references('navigation_menu_types_id')->on('navigation_menu_types');
$table->timestamps(); });
NavigationMenu Model.php
class NavigationMenu extends Model {
protected $primaryKey = 'navigation_menus_id';
public function navigationType()
{
return $this->belongsToMany(NavigationMenuType::class,'navigation_menus_navigation_types','navigation_type_id',' navigation_menu_id');
}}
Navigation Menu Type Model.php
class NavigationMenuType extends Model{
protected $primaryKey = 'navigation_menu_types_id';
public function navigationMenu()
{
return $this->belongsToMany(NavigationMenu::class,'navigation_menus_navigation_types',' navigation_menu_id','navigation_type_id');
}}
PagesNavigation Controller.php
public function syncNavtypes(){
$this->seletedNavigationMenu = NavigationMenu::find($this->navMenuId);
$this->seletedNavigationMenu->navigationType()->sync($this->navTypeId);
$this->modelSyncNavigationTypesVisible = false;
$this->reset();
$this->resetValidation();}
I think the problem in your relation:
public function navigationType()
{
return $this->belongsToMany(NavigationMenuType::class,'navigation_menus_navigation_types','navigation_type_id',
' navigation_menu_id'); // here!!
}
the thing is that you have added extra space to the begin of the column name,
currently laravel will take it to the letter!!
you have to just remove the extra space.
public function navigationType()
{
return $this->belongsToMany(NavigationMenuType::class,'navigation_menus_navigation_types','navigation_type_id',
'navigation_menu_id');
}
Problem is fixed if there's no additional issue. You'd put an extra space in your relation -
' navigation_menu_id'
return $this->belongsToMany(NavigationMenuType::class,'navigation_menus_navigation_types','navigation_type_id','navigation_menu_id');

Laravel hasMany and belongsToMany relationship

I have struggled with my Laravel relationships.
So I have 3 tables:
Users
Countries
countries_user
As you can see relation is countries_user. Now every time gives error like:
Illuminate\Database\QueryException: SQLSTATE[42S22]: Column not found:
1054 Unknown column 'countries.user_id' in 'where clause' (SQL: select
from countries where countries.user_id = 1 and countries.user_id is not null) in file
C:\xampp\htdocs\gManager\vendor\laravel\framework\src\Illuminate\Database\Connection.php
on line 671
I understand the problem is that it's looking in countries and not in countries_user. How to define where I want to search the relation?
Here is my User model
public function countries()
{
return $this->hasMany('App\Models\Countries');
}
And my Countries Model
public function users()
{
return $this->belongsToMany(User::class);
}
Try specifying the table name
public function users()
{
return $this->belongsToMany(User::class, 'countries_user');
}
And the inverse relation should also be belongsToMany
public function countries()
{
return $this->belongsToMany(Countries::class, 'countries_user');
}
And also specify the table property on Countries model
class Countries extends Model
{
protected $table = 'countries';
//...
}
The countries relationship should be belongsToMany too.
Instead of
public function countries()
{
return $this->hasMany('App\Models\Countries');
}
put
public function countries()
{
return $this->belongsToMany('App\Models\Countries');
}

SQLSTATE[42S22]: Column not found: 1054 Laravel

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

My Laravel relationship problems

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 .

Base table or view not found: Many to many relation laravel

I have two models setup in many to many relation with pivot tabel climbincludeds_tour:
Tour.php
class Tour extends Model
{
protected $table = 'tours';
public function climbIncluded(){
return $this->belongsToMany('App\ClimbIncluded',
'climbincludeds_tour',
'tour_id', 'cincluded_id');
}
}
ClimbIncluded.php
class ClimbIncluded extends Model
{
protected $table = 'climbincludeds';
public function tours()
{
return $this->belongsToMany('App\Tour');
}
}
And I have a delete button on view attached to destroy method in ClimbIncludedController.php
public function destroy(ClimbIncluded $climbIncluded)
{
$climbIncluded->tours()->detach();
$climbIncluded ->delete();
Session::flash('success','Item sucessfully deleted !');
return redirect()->route('climb.ie');
}
When I want to delete a record laravel returns an error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'peak.tour_trek_included'
doesn't exist (SQL: delete from `tour_trek_included` where `trek_included_id` = 1)
If I remove or comment out the $climbIncluded->tours()->detach(); from the destroy method, laravel deletes the record without any error. I have passed name of pivot table as second argument to belongsToMany method also. What am I missing here ?

Categories