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

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 ?

Related

Laravel 8 - I got this error 'SQLSTATE[42S02]' how can I solve this?

I'm trying to do follow system without any laravel libray. I got this error when I submit form. How can I fix it? I think error is about my user model and my follow model relationship but I couldn't solve.
My error is:
SQLSTATE[42S02]: Base table or view not found: 1146 Table
'muzik.follows' doesn't exist (SQL: insert into follows
(following_id, follower_id, updated_at, created_at) values
(12, 30, 2021-04-02 22:32:50, 2021-04-02 22:32:50))
My User model contains the following relationship:
public function follows(){
return $this->hasMany('App\Models\Follow');
}
My User model contains the following relationship:
public function user(){
return $this->belongsTo('App\Models\User');
}
My controller is:
public function follow(Request $request){
$request->validate([
'follower_id'=>['required'],
'following_id'=>['required'],
]);
$follower_id = $request->follower_id;
$following_id = $request->following_id;
$save = Follow::create([
'following_id' => Auth::user()->id,
'follower_id' => $follower_id,
]);
if($save){
return back();
}else{
return back();
}
}
check your "Follow" model, you may needs specify table name with:
protected $table='tableWhereYouSaveFollows';
Did you check your migration I think you did not create the Follow table if you did try to Just specify your table in the model as such:
class follows extends Model{
public $table = "follow";
I think your follow table does not exist, first create your follow table and then add this to your follow model:
use Illuminate\Database\Eloquent\Model;
class Follow extends Model
{
protected $table="follows";
//---Guarded
protected $guarded = [];
//---User Function
public function user(){
return $this->belongsTo('App\Models\User');
}
}

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

Eloquent ORM dynamic table, creating via model fails to select table

On the REST API am building based on slim3, I use route parameters to dynamically select a tenant to do certain crud actions on.
The model:
class Customer extends Model {
protected $table = '';
protected $fillable = ['some', 'fields'];
public function setTable($table) {
$this->table = $table;
}
public function getTable() {
return $this->table;
}
}
Selecting and updating entries works (properly) like this:
// selects properly from $tableName table
$kd = new Customer;
$kd->setTable($tableName);
$data = $kd->whereEmail($args['email'])->firstOrFail();
Creation fails, using the same approach:
$kdc = new Customer;
$kdc->setTable($tableName); // it should use dbname.prefix_$tableName same as above
$kdc->create($customerData);
// fails with error Base table or view not found: 1146 Table 'dbname.prefix_' doesn't exist
I have checked that create() successfully calls getTable() from the Model and gets proper value. But it seems not to use it...

How to save In Pivot Table in Laravel

How to save data to pivot table in laravel , I have two tables has many-to-many relationship , so i create pivot table , I tried the sync() method to insert but it keep gives me this exception:
"message": "Call to a member function sync() on null",
"exception": "Symfony\Component\Debug\Exception\FatalThrowableError",
here is Contract Model :
class Contract extends Model
{
public function skills(){
$this->belongsToMany(RequiredSkills::class , 'contract_skills')->withTimestamps();
}
}
and here is RequiredSkills Model :
class RequiredSkills extends Model
{
public function contract(){
$this->belongsToMany(Contract::class , 'contract_skills');
}
}
and here is the controller :
class RequiredSkillsController extends Controller
{
public function store(Request $request){
$contract = new Contract();
$data = $request->all();
$requiredSkills = RequiredSkills::create([
'contract_id'=>$data['contract_id'],
'skills_tag'=>$data['skills_tag'],
'user_id'=>auth()->guard('api')->user()->id
]);
$contract->skills()->sync($requiredSkills->id);
return $requiredSkills;
}
}
how to solve the exception ?
You don't have to write data to the relationship table laravel does it for you
When using the 'sync ()' function Laraval will automatically record the relationship in the "contract_skills" table.
You are not writing Contract to the database so it has no ID, so you will not be able to link
Contract and Skills need to be recorded before you can call
the sync () function will execute the following insert:
insert into [contract_skills] ([contract_id], [skill_id]) values (1, 1)
I would do the store function as follows
class RequiredSkillsController extends Controller
{
public function store(Request $request){
//Create Contract in database
$contract = Contract::create($request->contract);
//Get skills id to link with contract
$data = $request->skills;
//syncs with additional data
$contract->skills()->sync(array_column($data, 'id'), ['user_id'=>auth()->guard('api')->user()->id]);
return $contract->refresh()->skills;
}
}

Laravel Eager Loading One to Many Relationship

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

Categories