I am trying to apply where condition on joined table, but I'm getting this error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'cts.plant' doesn't exist (SQL: select * from tbl_complaint where exists (select * from tbl_plant where tbl_complaint.made_in_plant = tbl_plant.plant_id and sap_code = 99999) order by created desc limit 50 offset 0)
My model classes looks something like this:
Main Model
class Complaint extends Model {
protected $connection= 'first';
protected $table = 'complaint';
protected $primaryKey = 'complaint_id';
public function customerPlant() {
return $this->hasOne(Plant::class, 'plant_id', 'customer_plant_id')
->select('plant_id', 'sap_code', 'plant_name');
}
}
Connected Model
class Plant extends Model {
protected $connection= 'second';
protected $table = 'plant';
protected $primaryKey = 'plant_id';
public function getKeyName() {
return 'plant_id';
}
}
Data retrieval:
$query = Complaint::with([
'madeInPlantId']
$query = Complaint::whereHas('madeInPlant', function($query){
$query->where('sap_code','=','99999');
});
$query->get();
I think that problem is I'm not specifying that connected table is in another database.
if your tables are on the same server but different databases, you can do this.
class Complaint extends Model {
protected $table = 'cts.complaint';
protected $primaryKey = 'complaint_id';
public function customerPlant(){
return $this->hasOne(Plant::class, 'plant_id', 'customer_plant_id')
->select('plant_id', 'sap_code', 'plant_name');
}
}
class Plant extends Model{
protected $table = 'otherdatabase.plant';
protected $primaryKey = 'plant_id';
public function getKeyName() {
return 'plant_id';
}
}
Related
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);
i have 2 model Article and ArtCategories
I made the one-to-many relation between two model using belongsTo() and hasMany(). hasMany() relation works perfectly but belongTo() doesn't work. Does anyone know where did I make a mistake?
.
Code model
class ArtCategories extends Model
{
protected $table = 'pjt_categories_article';
protected $primaryKey = 'cate_id';
protected $fillable = ['cate_id','categories'];
public function Article(){
return $this->hasMany(Article::class);
}
}
class Article extends Model
{
protected $table = 'pjt_article';
protected $primaryKey = 'article_id';
protected $fillable = ['article_id','title','descriptions','username','cate_id','status','visit','reference'];
public function ArtCategories(){
return $this->belongsTo(ArtCategories::class,'cate_id');
}
public function admin(){
return $this->belongsTo(Admin::class);
}
}
This is DB structure Table up is pjt_article ,table down is pjt_categories_article
Result
$art = Article::findOrFail($article_id);
$cate = ArtCategories::pluck('categories', 'cate_id');
dd($art);
Relation Not working
You should add foreign key in relation method of ArtCategories
class ArtCategories extends Model
{
protected $table = 'pjt_categories_article';
protected $primaryKey = 'cate_id';
protected $fillable = ['cate_id','categories'];
public function article(){
return $this->hasMany(Article::class, 'cate_id');
}
}
Now fetch article with ArtCategories as:
$art = Article::with('ArtCategories')->findOrFail($article_id);
$cate = ArtCategories::pluck('categories', 'cate_id');
dd($art);
As laravel convention Article() method should be articles() and ArtCategories() should be artCategory().
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]);
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');
}
}
I'm trying to bind multiple models to a form. Currently, I have 4 models:
<?php
class DemDataSet extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'DEMDataSet';
protected $primaryKey = 'pk_DEMDataSet';
public function DemographicReport(){
return $this->hasOne('DemographicReport','fk_DemDataSet','pk_DemDataSet');
}
}
class DemographicReport extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'DemographicReport';
protected $primaryKey = 'pk_DemographicReport';
public function DemDataSet(){
return $this->belongsTo('DemDataSet','fk_DemDataSet','pk_DemDataSet');
}
public function dAgency(){
return $this->hasOne('dAgency','fk_DemographicReport','pk_DemographicReport');
}
}
class dAgency extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'dAgency';
protected $primaryKey = 'pk_dAgency';
public function DemographicReport(){
return $this->belongsTo('DemographicReport','fk_DemographicReport','pk_DemographicReport');
}
public function dAgency_10(){
return $this->hasMany('dAgency_10','fk_dAgency','pk_dAgency');
}
}
class dAgency_10 extends Eloquent {
public $timestamps = false;
protected $connection = 'epcr_dem_data';
protected $table = 'dAgency_10';
protected $primaryKey = 'pk_dAgency_10';
public function dAgency(){
return $this->belongsTo('dAgency','fk_dAgency','pk_dAgency');
}
}
?>
And I'm passing it to my view through my controller like so:
public function index()
{
//THIS is the line I need help with (I think):
$agency = dAgency::with('dAgency_10','DemographicReport')->find(1);
//for troubleshooting:
echo "<pre>",print_r(dAgency::with('dAgency_10','DemographicReport')->find(1)->toArray()),"</pre>";
return View::make('test')
->with('agency', $agency);
}
I'm able to bind everything except for data from the DemDataSet model, which I can't even figure out how to establish the relationship between it and my dAgency model. So basically, I just want the fields in the DemDataSet model to be available to my view, then obviously I want to be able to perform all the CRUD operations eventually.
Looking at your models, you should just be able to access it via the DemographicReport.
i.e.,
$dataset = $agency->DemographicReport->DemDataSet;