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.
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);
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');
}
I'm beginning to think why did Laravel implement relationships to their framework, they've never worked for me and their a huge stress to fix when they break. This is the 5th time my relationships are returning null, even when ensuring I've set them up properly?
class UserStats extends Authenticatable
{
protected $table = 'habbo_user_stats';
public $timestamps = false;
protected $guarded = ['id'];
public function user()
{
return $this->belongsTo(User::class, 'id');
}
}
And
class User extends Authenticatable
{
protected $table = 'habbo_users';
public $timestamps = true;
protected $guarded = ['id'];
public function stats() {
return $this->belongsTo(UserStats::class, 'user_id');
}
}
although, when calling
{{ $user->stats->some_column }}
stats is returning null... $user isn't null.
I think you have to define the owner of the relationship too. Ie:
public function stats() {
// $this->hasMany OR $this->hasOne, depending on your use case.
return $this->hasMany(UserStats::class, 'user_id');
}
We need to know here, does the user have many userstats? or the userstats have many user records? what are you planning to do here?
Here are things I noticed about your code
Your database structure is wrong. (need migrations to verify this)
Extending UserStatus from Authenticable
you have guarded id
Your relationships definitions are not correct.
To confirm we would need to look into the database structure and migrations.
If a userstat have many users and a user belongs to 1 userstat.
the migrations will be
users table will have a user_stat_id and userstats table wont have a user_id
the code will look like this.
UserStatus.php
class UserStats extends Model
{
protected $table = 'habbo_user_stats';
public $timestamps = false;
protected $guarded = ['id'];
public function users()
{
return $this->hasMany(User::class, 'user_stat_id');
}
}
User.php
class User extends Authenticatable
{
protected $table = 'habbo_users';
public $timestamps = true;
protected $guarded = ['id'];
public function stat() {
return $this->belongsTo(UserStats::class, 'user_stat_id');
}
}
I already tried several things but I can't get this to work. I want to be able to make something like this {{ $user->city->name }}
My user model:
<?php
namespace App;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
public $timestamps = false;
protected $table = 'users';
protected $fillable = ['id_city', 'name', 'email', 'password', 'admin'];
protected $hidden = ['password', 'remember_token'];
public function city()
{
return $this->belongsTo('App\City');
}
}
And this is my City model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class City extends Model
{
public $timestamps = false;
protected $table = 'cities';
protected $fillable = ['name', 'slug'];
public function users(){
return $this->hasMany('App\User');
}
}
And I'm trying to use {{ $user->city->name }} on my view but it doesn't work, it returns an error ErrorException: Trying to get property of non-object (View: .../views/app/text.blade.php).
What should I do?
Within your belongsTo relationship, Eloquent tries to match city_id as the foreign key by default as you don't pass the second argument.
However, according to your fillable attributes, what you have as the foreign key is actually id_city.
For the User model,
public function city()
{
return $this->belongsTo('App\City', 'id_city');
}
For the City model,
public function users(){
return $this->hasMany('App\User', 'id_city', 'id');
}
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');
}