I have two tables. One contains the user and the other contains meetings.
Each meeting belongsTo exact one User.
Meetings
class Meeting extends Model {
protected $table = 'meetings';
protected $primaryKey = 'owner_id';
/**
* A meeting belongs to exact one User
* #return \Illuminate\Database\Eloquent\Relations\BelongsTo
*/
public function user(){
return $this->belongsTo(User::class, 'id');
}}
User
class User extends Authenticatable
{
use Notifiable;
protected $table = 'users';
protected $primaryKey = 'id';
/**
* One User can have many Meetings
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function meetings(){
return $this->hasMany(Meeting::class, 'owner_id');
}
I fetch the data with
$meetings = Meeting::with('user')->get();
But somehow i don't get the related user. It just iterates over all users in the database and breaks if no more user is given.
What the heck am I doing wrong? O.o
Let try to change it:
public function user(){
return $this->belongsTo(User::class, 'id');
}
To
public function user(){
return $this->belongsTo(User::class, 'owner_id', 'id');
}
Looking at your Meeting model there are 2 strange things:
protected $primaryKey = 'owner_id';
Why is that? Shouldn't it be id here?
Second thing:
public function user(){
return $this->belongsTo(User::class, 'id');
}
probably here instead of id you should user owner_id.
So to sum up it seems you set wrong keys for primary key and for relationships and probably that's the reason relationship doesn't work as it should.
Related
Eager loading not pulling relation model.
Hi, Im using Laravel 6. Our database was created with Zend so our model is a bit strange; I have to set the primary keys.
// Customer model
protected $table = 'customer';
protected $primaryKey = 'Customer_ID';
/**
* Get all appointments for the customer.
*/
public function appointments()
{
return $this->hasMany('App\Appointment');
}
Then for the appointments
protected $table = 'appointment';
protected $primaryKey = 'Appointment_ID';
/**
* Get the customer assigned to this appointment.
*/
public function customer()
{
return $this->belongsTo('App\Customer');
}
Now, in a controller:
$appointments = App\Appointment::with('customer')->take(5)->get();
return response()->json($appointments, 200);
The array has the appointments but customer is null:
{... Customer_ID: 1234, customer: null}
Any ideas? Thanks
When you create the relationship in the model, you can tell laravel which is the field of the foreign key.
If you do not do it, laravel supposes the foreign key is id, which is not your case.
The definition of the relationship should becomes:
public function customer()
{
return $this->belongsTo('App\Customer', 'Customer_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 want to get the name of User where belongs the foreign key using Laravel Eloquent.
I have posts Model:
Class Posts Extends Eloquent{
protected $table = 'posts';
protected $fillable = array('title, image, text, user_id');
public $timestamps = false;
}
and
User Model:
class User extends Authenticatable
{
use Notifiable;
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = [
'name', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
}
I want to send to controller the value of user name, title, text, image to view.
public function index(){
// get all the bears
$posts = Posts::all();
return View::make('welcome', compact('posts'));
}
Define the one to many relationship between the models as,
class Posts extends Model
{
public function user(){
return $this->belongsTo('App\User');
}
// Whatever your code in Post model
}
class User extends Model
{
public function posts(){
return $this->hasMany('App\Post');
}
// Whatever your code in User model
}
as explained in the documentation here. Now you can get the name of the user that the post is belonged to each post.
Define the route as
Route::get('/all-posts','PostController#getAllPosts')->name('get_all_posts');
Write the controller class to get the posts
class PostController extends Controller
{
public function getAllPosts() {
$posts = Posts::all();
foreach ($posts as $post){
$username = $post->user->name;
//do something with $username
}
return view('all_posts')->with('detailed_posts');
//here the $detailed_posts can be defined in the 'do something' above
}
}
Here at do something you can create a new array of username and pass it to the view,
or
set the PostController as,
class PostController extends Controller
{
public function getAllPosts() {
return view(all_posts);
}
}
and then set the all_posts.blade.php to directly access the username in the view using blade syntax as follow ,
<html>
<div>
<h1>All Posts</h1>
#foreach (App\Post::all() as $post)
<span> Title : {{ $post->title}}</span>
<span> Username: {{$post->user->name}}</span>
.......
#endforeach
</div>
</html>
To set up the relationship for the Users -> Posts, then you can use hasMany
public function posts(){
return $this->hasMany('App\Post');
}
This will look for any user_id on the posts table. If it's named differently, then you can pass it in as the second parameter.
public function posts(){
return $this->hasMany('App\Post', name_of_column_in_post_table, name_of_column_in_user_table);
}
In the posts table, you want either hasOne or belongsTo. Both work the same way:
public function users() {
return $this->belongsTo('App\User', name_of_column_in_user_table, name_of_column_in_post_table);
}
You can then get the user information by doing $post->user->name
In the Model Class add the Relation like
Class Posts Extends Eloquent{
protected $table = 'posts';
protected $fillable = array('title, image, text, user_id');
public $timestamps = false;
public function user()
{
return $this->belongsTo('App\User','user_id);
}
}
Now in the controller or view in every instance of Post you can use:
By Example
$post->user
Read the documentation about many to one relationship and even eager loading.
I have a two table named users and profile . In profile table there is a column named userID.Now i want to this userID column takes value from users table's id.I have done database relationships part.But can not retrieve data with view.I have searched but i have not found any satisfying answer according my issue.
By the way i am new in Laravel.I have tried so far
User Model:
class User extends Authenticatable
{
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $table ="users";
protected $fillable = [
'userName', 'email', 'password',
];
/**
* The attributes that should be hidden for arrays.
*
* #var array
*/
protected $hidden = [
'password', 'remember_token',
];
public function userProfile(){
return $this->hasOne('App\Profile');
}
}
Profile Model:
class Profile extends Model
{
//
protected $table = "profiles";
public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic"];
public function user(){
return $this->belongsTo('App\User');
}
}
And i am trying to retrieve userID with {{$profile->userID}}.I really don't know where is the problem and how to do this?
you will need to tell laravel to get the relationship model like this
$profile = Profile::find(1);
$userID = $profile->user->id;
edit:
from the docs
model is automatically assumed to have a user_id foreign key.
which in your case is userId so change your hasOne and belongsTo methods to tell laravel the name of foreign_key you are using
public function profile()
{
return $this->hasOne('App\Profile', 'userId');
}
public function user()
{
return $this->belongsTo('App\User', 'userId');
}
Please add userID to the fillable array of profiles.
Please check below sample code to do the same.
public $fillable = ["firstName","lastName","middleName","DOB","gender","featuredProfile","email","phone","summary","profilePic","userID"];
I have my database (=model) structure like that:
game:
lot (typeof Lot)
places (array type of Place)
place_id // just a number of a lot in some game
user_id
What should I do to call in everywhere like this:
User::find(1)->games() // returns Game collection where user has places
?
Models are:
class Place extends Model
{
protected $fillable = ['place_id', 'user_id', 'game_id'];
public function user() {
return $this->belongsTo(User::class);
}
public function game() {
return $this->belongsTo(Game::class);
}
}
User:
class User extends Model implements AuthenticatableContract,
AuthorizableContract,
CanResetPasswordContract
{
use Authenticatable, Authorizable, CanResetPassword;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'users';
/**
* The attributes that are mass assignable.
*
* #var array
*/
protected $fillable = ['name', 'email', 'steam_id', 'avatar'];
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
protected $hidden = ['remember_token'];
/**
* Get all of the tasks for the user.
*/
public function items()
{
return $this->hasMany(SteamItem::class);
}
public function places() {
return $this->hasMany(Place::class);
}
}
The Game:
class Game extends Model
{
protected $fillable = ['lot_id'];
public function lot() {
return $this->belongsTo(Lot::class);
}
public function places() {
return $this->hasMany(Place::class);
}
}
Now I use this code in my User class:
public function games() {
return Game::with(['places' => function ($query) {
$query->where('user_id', $this->id);
}]);;
}
It doesn't work, because I need to make it as a relationship method, but with method returns a query builder.
In the finals I must call $user->games and it should return me all the games user linked to through place.
Okay. I think I understand now.
User has many Place. Place belongs to User.
Place belongs to Game. Game has many Place.
You can try this:
$user = User::with('places.game.lot')->find(1);
This will fetch the User and eager load all the relationships. Because Place belongsTo a Game, which in turn belongs to Lot, you can then do this:
#foreach ($user->places as $place)
<img src="{{$place->game->lot->imageUrl}}" />
#endforeach
Also, place is actually a pivot table, and you can take advantage of Eloquent's many-to-many relationship, which I would recommend reading about.