Laravel looking for the wrong table - php

I have specified the table name in the model class.
Laravel 5.6, PHP 7
namespace App;
use Illuminate\Database\Eloquent\Model;
class SizeProduct extends Model
{
protected $table = 'size_product';
protected $fillable = ['product_id', 'size_id'];
}
This is my migration:
class CreateSizeProductTable extends Migration
{
public function up()
{
Schema::create('size_product', function (Blueprint $table) {
//some code here
});
}
public function down()
{
Schema::dropIfExists('size_product');
}
But i still get this error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'db_name.product_size' doesn't exist

maybe sizeproduct is your pivot table for manytomany relation, so as described here, The pivot table is derived from the alphabetical order of the related model names (so in your case product comes first).
You can change it in relation defining code:
public function products()
{
return $this->belongsToMany(Size::class,'size_product');
}
Or you may prefer to create separate migration for your pivot table.

Related

Laravel 7 One To Many Relations?

Below are all of the models, migrations and controller.
Donation Model
class Donation extends Model
{
protected $guarded =[];
public function users(){
return $this->hasMany(User::class);
}
public function items(){
return $this->belongsTo(DonationItems::class);
}
}
Donation Items Model:
class DonationItems extends Model
{
protected $guarded=[];
public function donation(){
return $this->hasMany(Donaition::class);
}
}
Donation Items Migration:
public function up()
{
Schema::create('donation_items', function (Blueprint $table) {
$table->id();
$table->string('category');
$table->timestamps();
});
}
Donation Migration:
public function up()
{
Schema::create('donations', function (Blueprint $table) {
$table->id();
$table->string('item');
$table->unsignedInteger('user_id');
$table->unsignedInteger('donation_item_id');
$table->timestamps();
});
}
In my controller I want to access the items as follows:
$don = Donation::all();
$don->items;
But I'm unable to achieve this.
Its not working because laravel follows one rule for relationships:
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.
So you can try by supplying local and foreign id
So it would look something like this
Donation Model
class Donation extends Model
{
protected $guarded =[];
public function users(){
return $this->hasMany(User::class);
}
public function items(){
return $this->belongsTo(DonationItems::class, 'donation_item_id', 'id');
}
}
Donation Items Model:
class DonationItems extends Model
{
protected $guarded=[];
public function donation(){
return $this->hasMany(DonationItems::class, 'id', 'donation_item_id');
}
}
I am writing from my head you might need to swap local and foreign ID's

Create Many to Many Polymorphic Relationship using custom table

How can I create a Many to Many relationships using the custom polymorphic table?
model_has_tags
$table->increments('id');
$table->integer('tag_id';
$table->string('model_type');
$table->integer('model_id');
tags
$table->increments('id');
$table->string('name');
user
$table->increments('id');
$table->string('full_name');
I try this but not working.
Tag Model
public function users()
{
return $this->morphedByMany(User::class, 'model');
}
User Model
public function tags()
{
return $this->morphToMany(Tag::class, 'model');
}
error :
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'stormport.models' doesn't exist (SQL: select `tags`.*, `models`.`model_id` as `pivot_model_id`, `models`.`tag_id` as `pivot_tag_id`....
How to solve this?
Found the solution:
User Model
public function tags()
{
return $this->morphToMany(Tag::class, 'model', 'model_has_tags');
}

Handling mapping table in laravel eloquent

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.

Specific role relations

I work on one project with Laravel 5.2 and Entrust package for ACL.
In this project I need for one Role ('venue_owner') in which venue is owner. I have also table called venue and I have no idea how to make this relations, because table users is general for all type of users.
How to make this relations to know what user from role venue_owner is owner of what venues ?
Have you created your Migrations yet by running: php artisan enthrust:migration? if not it, run it and then inside the file that is generated, add your own tables like below within the up() Method of the Enthrust Migration File:
<?php
public function up() {
// SOME OTHER TABLE CREATION CODES...
Schema::create('venue_owner', function (Blueprint $table) {
$table->increments('id');
$table->integer("user_id")->unsigned();
$table->timestamps();
// CREATE THE ASSOCIATION/RELATIONSHIP USING FOREIGN KEY
$table->foreign('id')
->references('id')
->on('venue')
->onDelete('cascade');
});
Schema::create('venues', function (Blueprint $table) {
$table->increments('id');
$table->integer("venue_owner_id")->unsigned();
$table->string("venue");
$table->timestamps();
// CREATE THE ASSOCIATION/RELATIONSHIP USING FOREIGN KEY
$table->foreign('venue_owner_id')
->references('id')
->on('venue_owner');
});
}
public function down() {
// OTHER DROP COMMAND CODES...
Schema::drop('venue_owner');
Schema::drop('venues');
}
Then in your Eloquent Model Class you can explicitly set the $this->hasMany() like so:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class VenueOwner extends Model {
/**
* GET ALL THE venues FOR THE venue_owner .
*/
public function venues() {
return $this->hasMany('App\Venues');
}
/**
* GET ALL THE user FOR THE venue_owner .
*/
public function user() {
return $this->hasOne('App\User');
}
And in your Venues Eloquent Model Class, you do something like:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Venues extends Model {
/**
* GET THE venue_owner FOR venue(s).
*/
public function venueOwner() {
return $this->belongsTo('App\VenueOwner');
}
Last but not least in your Users Eloquent Model Class, you do something like:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Users extends Model {
/**
* GET THE user Information FOR venue_owner.
*/
public function venueOwner() {
return $this-> hasOne('App\VenueOwner');
}
Now, you can get all information about the venue_owner and his venues and roles & permissions using the user_id.

Laravel Eloquent one-to-one relationship setup

I am setting up a one to one relationship in a laravel application, but I am getting the error "trying to get property of non-object" when I try to reference a related table.
My Contractor.php model:
class Contractor extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'contractor';
function profile() {
return $this->hasOne('ContractorProfile');
}
}
My ContractorProfile.php model:
<?php
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class ContractorProfile extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'contractor_profile';
public function contractor() {
return $this->belongsTo('Contractor');
}
}
here is the snippet of my view file
show.blade.php
<div>
<h4>{{ $contractor->profile->tag_line }}</h4></p>
</div>
If I just call $contractor->profile the page loads but nothing is echoed back. If I add the ->tag_line, I get the "trying to get property of non-object" error. tag_line is a column name inside of my contractor_profile table.
Do you see an error that I am making?
TIA
EDIT: Database info:
Schema::create('contractor', function ($table) {
$table->increments('id');
$table->integer('hba_number')->nullable();
$table->integer('msn')->nullable();
$table->string('type')->default("");
$table->string('name')->default("");
$table->string('address_1')->default("");
$table->string('address_2')->default("");
$table->string('city')->default("");
$table->string('state')->default("");
$table->string('zip')->default("");
$table->string('country')->default("");
$table->string('phone')->default("");
$table->string('website')->default("");
$table->integer('company_id')->nullable();
$table->integer('user_id');
$table->timestamps();
$table->softDeletes();
});
Schema::create('contractor_profile', function ($table) {
$table->increments('id');
$table->integer('contractor_id');
$table->string('tag_line')->default("");
$table->string('story')->default("");
$table->string('area_of_operation')->default("");
$table->text('experience')->default("");
$table->text('education')->default("");
$table->text('insurance_verified')->default("");
$table->timestamps();
$table->softDeletes();
});
The issue may be because you're using a non-standard table name for your Contractor model. Try defining the relationship in your ContractorProfile model by specifying the second parameter to belongsTo:
return $this->belongsTo('Contractor', 'contractor_id');
You may also need to perform the same mapping on the Contractor model as well:
return $this->hasOne('ContractorProfile', 'contractor_id');

Categories