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');
}
}
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 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 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.
Ok so I am trying to have use the Eloquent method "firstOrCreate" within another Eloquent model.
FriendRequest Eloquent
class FriendRequest extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
public $table = 'requests';
protected $guarded = array('id');
protected $softDelete = true;
public function friend() {
return $this->hasOne('User', 'id', 'friend_id');
}
public function user() {
return $this->hasOne('User', 'id', 'user_id');
}
public function accept() {
// FIRST YOU MUST MARK REQUEST AS ACCEPTED
// THEN SOFT DELETE REQUEST SO IT DOESN'T
// SHOW UP AS ACTIVE FRIEND REQUEST
$this->accepted = '1';
$this->save();
// CREATE FRIENDSHIP USER -> REQUESTED
$friend = Friend::firstOrNew(array('user_id' => Auth::user()->id, 'friend_id' => $this->friend_id));
$friend->save();
// CREATE FRIENDSHIP REQUESTED -> USER
$friend2 = Friend::firstOrNew(array('user_id' => $this->friend_id, 'friend_id' => Auth::user()->id));
$friend2->save();
// SOFT DELETE REQUEST BEING MARKED ACCEPTED
$status = $this->delete();
if (!$status):
return false;
else:
return true;
endif;
}
}
I've tried both firstOrCreate and firstOrNew as shown but with both times 'friend_id' and 'user_id' given in the array are set as '0'.
There is no default on the rows or indexes.
Here's the Friend Eloquent Model
class Friend extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
public $table = 'friends';
protected $guarded = array('id');
public function user() {
return $this->hasOne('User', 'id', 'user_id');
}
public function friend() {
return $this->hasOne('User', 'id', 'friend_id');
}
}
The create() method does mass assignment and this is a big security issue, so Laravel has a protection against it. Internally it has guarded = ['*'], so all your columns will be protected against mass assignment. You have some options:
Set the fillable columns of your model:
class User extends Eloquent {
protected $fillable = array('first_name', 'last_name', 'email');
}
Or set only the ones you want to keep guarded:
class User extends Eloquent {
protected $guarded = array('password');
}
You may, at your own risk also do:
class User extends Eloquent {
protected $guarded = array();
}
Also on the difference between the firstorcreate, and firstornew:
The firstOrNew method, like firstOrCreate will attempt to locate a record in the database matching the given attributes. However, if a model is not found, a new model instance will be returned. Note that the model returned by firstOrNew has not yet been persisted to the database. You will need to call save manually to persist it:
You can also go through the Facade and use the follwing:
class Settings extends Eloquent
{
protected $table = 'settings';
protected $primaryKey = 'name';
public static function get($settingName)
{
return Settings::firstOrCreate(array('name' => $settingName));
}
}
I believe you should put your accept() function in one of your controllers instead of the model. I'm not sure how and where you're calling this function, but I think it's in the wrong place.