hasManyThroughrelationship return wrong SQL sentence - php

I would like to get some data for tables that dont have a directly relation. The context is the following:
//** account_table **// Normal user, who can buy any book
account_id
account_info
//** book_table **// Books
book_id
account_id
author_id
//** author_table **// Author, who can write a lot of books (they will have more functions, this is the why i choose to create other table)
author_id
book_id
author_desc
The models that im using are:
class Account extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'account_table';
protected $primaryKey = 'account_id';
public function Book()
{
return $this->hasMany('Book', 'account_id');
}
public function Author()
{
return $this->hasManyThrough('Author', 'Book','account_id','book_id');
}
}
class Book extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'book_table';
protected $primaryKey = 'book_id';
public function Account()
{
return $this->belongsTo('Account','account_id');
}
public function Author()
{
return $this->hasOne('Author', 'author_id', 'author_id');
}
}
class Author extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'author_table';
protected $primaryKey = 'author_id';
public function Book()
{
return $this->belongsToMany('Book', 'author_id');
}
}
So to get this information i use the following code:
$user = Account::find(166); //user
dd($user->Author);
The ouput throw an error like this:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'book.id' in 'on clause' (SQL: select `author_table`.*, `book_table`.`account_id` from `author_table` inner join `book_table` on `book_table`.`id` = `author_table`.`book_id` where `book_table`.`account_id` = 166)
Seems that it is looking for a field (id) that does not exist in my database, however i have defined all primaryKeys in the models. What should i do to get author_desc information in this context ?
EDIT (other example):
When i use the following code it retrieve the same error:
$user = Account::find(166);
echo Book::find(3);

You've defined a one-to-one relationship of Book to Author with the hasOne() method and a many-to-many relationship between Author and Book with the belongsToMany() method. These should be inverse relationships, instead. Try replacing the belongsToMany()method with the belongsTo() method. Something like this:
class Account extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'account_table';
protected $primaryKey = 'account_id';
public function Book()
{
return $this->hasMany('Book', 'account_id');
}
public function Author()
{
return $this->hasManyThrough('Author', 'Book','account_id','book_id');
}
}
class Book extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'book_table';
protected $primaryKey = 'book_id';
public function Account()
{
return $this->belongsTo('Account','account_id');
}
public function Author()
{
return $this->hasOne('Author', 'author_id', 'author_id');
}
}
class Author extends Eloquent implements UserInterface, RemindableInterface {
protected $table = 'author_table';
protected $primaryKey = 'author_id';
public function Book()
{
return $this->belongsTo('Book', 'author_id');
}
}

Related

eloquent select all table with relationship many to many

I have 3 tables (workflow, user, workflow_user) and I would like to select the view column of the workflow_user table.
class Workflow extends Model
{
public function user()
{
return $this->belongsToMany(User::class,'workflow_user');
}
}
class User extends Model
{
public function works()
{
//return $this->belongsToMany(Role::class);
return $this->belongsToMany(Workflow1::class,'workflow_user');
}
}
workflow_user table
class WorkflowUser extends Model
{
protected $table = 'workflow_user';
protected $fillable = [
'workflow1_id','user_id','view'
];
protected $primaryKey = 'id';
public $timestamps = false;
}
To get the data from the workflow_user table I do this
$workflow = User::find($idconnect)->works()->orderBy('created_at','desc')->paginate(10);
When I make this request it does not give me the data of the workflow_user(workflow1_id,user_id,view) table.
If you have a model for the pivot table, you should have it extend the Pivot class and use it in the relationship's definition.
Also, you need to manually include the fields that are not the foreign ids in the query result.
class Workflow extends Model
{
public function user()
{
return $this->belongsToMany(User::class, 'workflow_user', 'workflow_id', 'user_id')
->using(WorkflowUser::class)
->withPivot(['id', 'view']);
}
}
class User extends Model
{
public function works()
{
return $this->belongsToMany(Workflow::class, 'workflow_user', 'user_id', 'workflow_id')
->using(WorkflowUser::class)
->withPivot(['id', 'view']);
}
}
workflow_user table
class WorkflowUser extends Pivot
{
protected $table = 'workflow_user';
protected $fillable = ['workflow_id', 'user_id', 'view'];
protected $primaryKey = 'id';
public $incrementing = true;
public $timestamps = false;
}
$workflow = User::findOrFail($idconnect)
->works()
->orderBy('created_at', 'desc')
->paginate(10);

Laravel eloquent with() returns null

namespace App;
use App\Model\Service\Area;
use App\Model\Bid\Service;
use Illuminate\Database\Eloquent\Model;
class Bid extends Model
{
protected $table = "bid";
protected $primaryKey = 'bid_id';
protected $guarded = [];
protected $with = ['services'];
public function services() {
return $this->hasMany(Service::class, 'bid_id');
}
public function area() {
return $this->belongsTo(Area::class, 'area_id', 'area_id');
}
}
namespace App\Model\Service;
use Illuminate\Database\Eloquent\Model;
class Area extends Model
{
protected $table = "location_area";
protected $primaryKey = 'area_id';
protected $guarded = [];
public function city()
{
return $this->belongsTo(City::class, 'city_id');
}
}
Area table Migration and data
Bid table Migration and data
When I am trying to access
Bid::with('area')->find(BID_ID);
It is returning Null
Query is firing wrong:
"select * from `location_area` where `location_area`.`area_id` in (0)"
But if I am doing like:
$bid = Bid::find(BID_ID);
dd($bid->area);
It returns Area table values. What is going wrong? Please Help me. I
am having this problem for a long time. Thank You in advance :)
you must be declared a method in your MID model
public function area()
{
return $this->belongsTo(Area::class, 'bid');
}
something like this
after this, you access area in with()
Bid::with('area')->find(BID_ID);
Change this function in your Bid model :
public function area() {
return $this->belongsTo(Area::class, 'area_id');
}

How to select foreign key value in Laravel

I've two tables one is car_category having the fields - id,type.
Another table named vehicle having field - c_id(FK Refers car - id).
Now I want to display the FK(c_id) value which is car-type.
I've below code in models,
class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany('Vehicle');
}
}
vehicle model,
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo('Car');
}
}
What 'll be my query for this? I've tried this code, results error.
$vehicles = "SELECT cars.cartype,vehicles.model FROM cars,vehicles
WHERE cars.id = vehicles.c_id";
How can I achieve this? Can anybody help me?
Try this
class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany(Vehicle::class, 'c_id');
}
}
The vehicle model
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(Car::class, 'c_id');
}
}
Eloquent determines the foreign key of the relationship based on the model name. In this case, the Car model is automatically assumed to have a car_id foreign key. If you wish to override this convention, you may pass a second argument to the method
https://laravel.com/docs/5.5/eloquent-relationships#one-to-one
To get the Car along with their Vehicle information you can do a query using Eager Loading
$result = Car::with('vehicles')->get();
To get the Car along with their Vehicle information you can do a query using Eager Loading
$result = Car::with('vehicles')->get();
One more correction you have specified class name as string literals without specifying FQN, relationships in models should be defined using fully qualified name
Car Model
class Car extends Model
{
protected $guarded = [];
protected $table = 'car_category';
public function vehicles()
{
return $this->hasMany(\App\Models\Vehicle::class);
}
}
Vehicle Model
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(\App\Models\Car::class);
}
}
Change from class car to class Car
After that you can select with Car::first(), the related table data can be found in Car::first()->vehicles
You can also add a where() method on models, if you have more than one record, use a foreach()
In Model,
class Vehicle extends Model
{
protected $guarded = [];
protected $table = 'vehicles';
public function cars()
{
return $this->belongsTo(Car::class, 'c_id');
}
}
In controller,
$vehicles = Vehicle::all();
return view('vehicles.vehicle',['vehicles'=>$vehicles]);

Laravel HasOne relationship empty

I am trying to create a relationship between Player and Roleplay and its returning null. I know for a fact it should be working because the following code works perfectly:
Roleplay::find(Auth::user()->id);
And returns the correct data, a full array of the correct data.
When trying to access it this way:
Auth::user()->roleplay->user_id;
It doesn't work, can someone help me find out why?
How do you know its empty?
Because {{var_dump(Auth::user()->roleplay)}} in blade view returns EMPTY
When using it the view I also get a undefined error.
Primary key of roleplay table (srp_user_statistics) is user_id, and the primary key of player table (users) is id
here is the code:
Player:
<?php
namespace App\Database\Frontend\User;
use Hash;
use Eloquent;
use \Illuminate\Auth\Authenticatable;
use \Illuminate\Contracts\Auth\Authenticatable as Authentication;
class Player extends Eloquent implements Authentication
{
use Authenticatable;
protected $primaryKey = 'id';
protected $table = 'users';
public $timestamps = false;
protected $fillable = [];
public function setPasswordAttribute($value)
{
$this->attributes['password'] = Hash::make($value);
}
public function setUsernameAttribute($value)
{
return $this->attributes['username'] = $value;
}
public function roleplay()
{
return $this->hasOne('App\Database\Frontend\User\Roleplay', 'user_id');
}
}
Roleplay:
use Eloquent;
class Roleplay extends Eloquent
{
protected $primaryKey = 'user_id';
protected $table = 'srp_user_statistics';
public $timestamps = true;
protected $fillable = [];
public function user()
{
return $this->belongsTo('App\Database\Frontend\User\Player', 'user_id', 'id');
}
public function government_role()
{
return $this->belongsTo('App\Database\Frontend\Roleplay\GovernmentRole', 'government_id');
}
}
I thinks you should add 'id' to hasOne() in the User model
public function roleplay()
{
return $this->hasOne('App\Database\Frontend\User\Roleplay', 'user_id', 'id');
}
And remove 'id' from belonsTo() in Roleplay model.
Side notes
This working
Roleplay::find(Auth::user()->id);
Is not a guarantee your relationships are set properly. All it does is
Roleplay::find(1); //$user->id returns an integer.

Laravel Eloquent Query Buliding

I have four tables and I am giving my table structure here
user_work['id', 'user_id', 'work_id']
work_sectors['id', 'name', 'status']
works['id', 'work_sector_id', 'work_type_id', 'work_duration_id', 'name']
users['id', ...]
And My Models are
class User extends Eloquent implements UserInterface, RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'users';
public function work()
{
return $this->belongsToMany('Work', 'user_work');
}
}
class Work extends \Eloquent {
protected $fillable = [];
protected $table_name = 'works';
public $timestamps = false;
public function user()
{
return $this->belongsToMany('User', 'user_work');
}
public function sector()
{
return $this->belongsTo('WorkSector', 'work_sector_id');
}
}
In my controller I have written this code
$user = User::with('language')->with('work')->find($userId);
Here I need name of work_sector table but probably I have written wrong code to get the sector name.
So please help me to write a proper function in this eloquent method in laravel 4.2.

Categories