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.
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);
im using laravel 7.24 and php 7.4 on my project
What i want to is fundementally creating relations between 3 table and using them in 'one' query.
to be specific i need to access 'ordered products' from my order detail page.
public function orderdetail($id)
{ //certainorder model access to 'ShoppingCard'model from below
$orderDetails = CertainOrder::with('ShoppingCard.shoppingCardProducts.product')
->where('ShoppingCard.id' , $id)->firstorFail();
return view('orderdetails', compact ('orderDetails'));
}
CertainOrder model access to 'ShoppingCard' model from top and in the ShoppingCard model it contains shoppingCardProducts function which you will see in below and with shoppingCardProducts function my 'products' table had a relation. the problem is something in relations is wrong and i can't get data from shoppingcardproduct
class ShoppingCard extends Model
{
protected $table = "shopping_card";
protected $fillable = ['id', 'user_id', 'created_at','updated_at'];
public function shoppingCardProducts()
{
return $this->hasMany('App\ShoppingCardProduct');
}
class CertainOrder extends Model
{
protected $table = "certain_orders";
protected $guarded = [];
public function shoppingCard()
{
return $this->belongsTo(ShoppingCard::class, 'sepet_id');
//sepet_id is a foreign key.
}
class ShoppingCardProduct extends Model
{
use SoftDeletes;
protected $table = "shopping_card_product";
protected $fillable = ['id', 'sepet_id', 'urun_id','quantity','price','status','created_at','updated_at','deleted_at'];
public function product()
{
return $this->belongsTo('App\Product');
}
I think you missed it somewhere in the code
class ShoppingCard extends Model
{
protected $table = "shopping_card";
protected $fillable = ['id', 'user_id', 'created_at','updated_at'];
public function shoppingCardProducts()
{
return $this->hasMany('App\ShoppingCardProduct');
}
public function CertainOrder(){
return $this->hasMany('path\to\model');
}
public function ShoppingCardProduct(){
return $this->hasMany('path\to\model');
}
}
class CertainOrder extends Model
{
protected $table = "certain_orders";
protected $guarded = [];
public function shoppingCard()
{
return $this->belongsTo('App\path\to\model', 'sepet_id');
//sepet_id is a foreign key.
}
}
class ShoppingCardProduct extends Model
{
use SoftDeletes;
protected $table = "shopping_card_product";
protected $fillable = ['id', 'sepet_id', 'urun_id','quantity','price','status','created_at','updated_at','deleted_at'];
public function ShoppingCard()
{
return $this->belongsTo('App\ShoppingCard');
}
}
and make the call this way
public function orderdetail($id)
{ //certainorder model access to 'ShoppingCard'model from below
$orderDetails = ShoppingCard::with('CertainOrder, ShoppingCardProduct')
->where('id' , $id)->firstorFail();
return view('orderdetails', compact ('orderDetails'));
}
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.
I'm try to create a relationship between albums and photos (an Album has many photos). Below is my controller and what my models look like. Interesting enough, the reverse relationship photo->album (belongsTo) works fine! but the album->photos returns an empty collection.
## The hasMany relationship does NOT work... I get an empty collection
<?php
class AlbumController extends BaseController
{
public function show(Request $request, $album_id)
{
$album = Album::find($album_id);
dd($album->photos);
}
}
## Results:
# Collection {#418
# items: []
# }
## The belgonsTo relationship works
<?php
class PhotoController extends BaseController
{
public function show(Request $request, $photo_id)
{
$photo = Photo::find($photo_id);
dd($photo->album);
}
}
<?php
namespace App;
use DB;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
use Moloquent;
class Album extends Moloquent
{
use RecordActivity, SoftDeletes;
protected $connection = 'mongodb';
protected $table = 'albums';
protected $collection = 'albums';
protected $primaryKey = "_id";
protected $dates = ['deleted_at'];
protected $fillable = ['user_id','name','is_private'];
public function photos()
{
// Neither seems to work
//return $this->embedsMany('Photo');
return $this->hasMany('App\Photo');
}
}
<?php
namespace App;
use DB;
use Jenssegers\Mongodb\Eloquent\SoftDeletes;
use Moloquent;
class Photo extends Moloquent
{
use RecordActivity, SoftDeletes;
protected $connection = 'mongodb';
protected $table = 'photos';
protected $collection = 'photos';
protected $primaryKey = "_id";
protected $dates = ['deleted_at'];
protected $fillable = ['album_id', 'user_id', 'name', 'folder', 'is_private', 'caption'];
protected $hidden = [];
// user and album belongsTo works
public function user()
{
return $this->belongsTo('App\User');
}
public function album()
{
return $this->belongsTo('App\Album');
}
}
The issue had to do with the fact that my IDs were ObjectID and it seems to be an issue with Jessengers Laravel MongoDB Drivers... we have actually decided to move back to MariaDB to fully utilize Eloquent/Relationships
I did the same thing as yours and i found that nothing wrong with Mongodb. Because Mongodb defined the "_id" as primary key and that's the reason it couldn't get the correct relationship: belongsTo and hasMany. So i did a small change by declared the $primaryKey = "id" on the top of parent Model and it worked fine
this worked for me.
/**
* #return HasMany
*/
public function tasks(): HasMany
{
return $this->hasMany(ProjectTask::class, 'project_id', 'idAsString');
}
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');
}
}