im trying to create a one to one relationship with the table user,student and teacher. The problem is, when i run LARAVEL TINKER, app\user::find('a123')->teacher it displays the b345 data and doesnt display NULL. New in Laravel. Thanks
Below is the table with their PK.
User table
user_id | type
a123 | 1
b345 | 2
Student table
student_id| name
a123 | Danny
Teacher table
teacher_id| name
b345 | Mr.Mark
and this BELOW is the models.
User Model
protected $primaryKey = 'user_id';
public function student(){
return $this->hasOne(student::class,'student_id');
}
public function teacher(){
return $this->hasOne(teacher::class,'teacher_id');
}
Student Model (Teacher model is just the same with teacher_id as PK)
protected $primaryKey = 'student_id';
public function User()
{
return $this->belongsTo(User::class,'user_id');
}
From you description, student should belongs to user, also teach
In User Model
public function student(){
return $this->hasMany(Student::class,'student_id');
}
In Student Model
public function user(){
return $this->belongsTo(User::class,'student_id');
}
Related
I have a problem showing data from 2 tables with an id, in laravel 6. My tables are "users" and "companies".
users
id
name
last name
companies
id
company
address
id_user
Model user
public function company()
{
return $this->hasOne('App\Company','id_user','id');
}
Model company
public function user()
{
return $this->belongsTo('App\User');
}
Controller
public function show($id)
{
$companies = Company::with('user')->find($id);
return view('clients.show', compact('companies'));
}
view
$companies->company
but the problem is that is not showing data from users table, can someone help me?
The foreign key name for user in companies table should be 'user_id' not 'id_user'
If you want to use custom column name make sure you pass it to the second argument of the relationship.
Model company:
public function user()
{
return $this->belongsTo('App\User', 'id_user');
}
I'm doing a project where every user can be assigned in a designation.
I did my work by using three model: User, Designation & UsersDesignation
The table structures are:
User:
id name email password
--- ----- ----- --------
1 User 1 u1#em.com kjasdkfjla
2 User 2 u2#em.com fksdjfghal
3 User 3 u3#em.com ghhaljaljl
Designation:
id name
--- -----
1 Faculty
2 Lecturer
3 Lab Instructor
UsersDesignation:
id userId designationId
--- ------ -------------
1 1 2
2 2 1
3 3 3
But I'm facing difficulty to get the designation of user from user object by establishing relationship.
I've tried in my Model so far:
User(model):
public function userDesignation()
{
$this->hasOne('App\UsersDesignation', 'id', 'userId');
}
UserDesignation(model):
public function user()
{
$this->belongsToMany('App\User', 'userId', 'id');
}
public function designation()
{
$this->belongsTo('App\Designation', 'designationId', 'id');
}
Actually I want to show the user profiles from user model with his/her designation. But the above way didn't work. I've no idea how to make this relation.
This is my view file:
<div>
{{ $user->userDesignation->designationId }}
</div>
The error I get every time
ErrorException (E_ERROR) App\User::userDesignation must return a
relationship instance. (View:
....\resources\views\profiles\show.blade.php)
I badly need this help!
If a User can only have 1 possible designation, you don't need a pivot table(UsersDesignation table).
Just put a designation_id in the users table and use the belongsTo and hasMany relationships.
User
public function designation()
{
return $this->belongsTo('App\Designation');
}
Designation
public function users()
{
return $this->hasMany('App\User');
}
Probably you need use a relationship many to many.
Example:
Table structures:
users:
id
name
email
password
designations:
id
name
designation_user
id
designation_id
user_id
Your model relationships
App\User:
public function designations()
{
return $this->belongsToMany('App\Designation');
}
App\Designation:
public function users()
{
return $this->belongsToMany('App\User');
}
To get the user's designations your call should look like this:
<div>
#foreach($user->designations()->get() as $designation)
{{ $designation->name }}
#endforeach
</div>
I have three entities:
User
Profile
Status
Summarized, users has a profile foreach status.
EXAMPLE
Users table records
user
id | name
1 user1
2 user2
3 user3
Status table records (this records is previously seeded)
status
id (PK) | title (string)
1 student
2 collaborator
3 teacher
Profile table structure
PROFILE
user_status_id (PK) (FK)
institution (string)
year (timestamp)
user1 is registered as student and fill your profile based on this status. After, he change your status to collaborator and fill another profile referred to this new status.
With that, i want to know:
When user1 was student?
the user1 was already collaborator ever?
Which institution user1 had frequented when he was student?
My first problem is:
How to model this relationship?
I'm not sure but think the above situation is a ternary relatinoship case, right?
And Second problem:
How build using Laravel Eloquent Relationships?
Let's start with relationship
class User extends Eloquent{
protected $table = 'user';
public $timestamps = true;
use SoftDeletingTrait;
public function status(){
return $this->hasOne(Status::class, 'user_id', 'id');
}
public function profile(){
return $this->hasMany(Profile::class,'user_id','id');
}
}
class Status extends Eloquent{
protected $table = 'status';
public $timestamps = true;
use SoftDeletingTrait;
public function user(){
return $this->belongsTo(User::class,'user_id','id');
}
}
class Profile extends Eloquent{
protected $table = 'profile';
public $timestamps = true;
use SoftDeletingTrait;
public function user(){
return $this->belongsTo(User::class,'user_id','id');
}
}
Above relation would somehow will get you what you need but just writing this relation made me question your table structure.
Suggestion DB Change For Better Relation
User
id, username, email, ........
Status
id, status, description, ........
Institutions
id, name, address, ............
User_Status_Institution
user_id,status_id,institution_id,timestamp,.......
This structure allows us that we can have Institution details even if there is no user_profile for that institution. Previous structure you had you can only have institution (name only) detail if and only if there is user profile. Also you can change institution (Name/address/phone etc) at one place and it will update it for all users.
As much as possible try that you can make information to be independent if possible because that reflects in models, object and relations.
Hope it makes sense.
I have a User table and need to allow for users to have a parent user.
the table would have the fields:
id
parent_id
email
password
How would I define this self referencing relationship in Eloquent ORM?
I had some success like this, using your exact DB table.
User Model:
class User extends Eloquent {
protected $table = 'users';
public $timestamps = false;
public function parent()
{
return $this->belongsTo('User', 'parent_id');
}
public function children()
{
return $this->hasMany('User', 'parent_id');
}
}
and then I could use it in my code like this:
$user = User::find($id);
$parent = $user->parent()->first();
$children = $user->children()->get();
Give that a try and let me know how you get on!
I had a chain of self referencing contracts (a contract can be continued by another contract) and also needed self referencing. Each contract has zero or one previous and also zero or one next contract.
My data table looked like the following:
+------------------+
| contracts |
+------------------+
| id |
| next_contract_id |
+------------------+
To define the inverse of a relationship (previous contract) you have to inverse the related columns, that means setting
* foreign key column on the model table
* associated column on the parent table (which is the same table)
<?php namespace App;
use Illuminate\Database\Eloquent\Model;
class Contract extends Model {
// The contract this contract followed
function previousContract()
{
// switching id and next_contract_id
return $this->belongsTo('App\Contract', 'id', 'next_contract_id');
}
// The contract that followed this contract
function nextContract()
{
return $this->belongsTo('App\Contract');
// this is the same as
// return $this->belongsTo('App\Contract', 'next_contract_id', 'id');
}
}
See http://laravel.com/docs/5.0/eloquent#one-to-one for further details.
Im really new to laravel, and im sure im doing something wrong
I have 2 tables. Cities And users_metadata
My cities table look like this
id | City |
1 | New York |
1 | Los Angeles |
users metadata
user_id | firt name | last name | cities_id |
1 | Jonh | Doe | 2 |
So my problem is when i create a relation i get New York, becaus the city id is matched with the user id
City model
class City extends Eloquent
{
public static $table = "cities";
public function profile()
{
return static::has_many('Profile');
}
}
profile model
class Profile extends Eloquent
{
public static $timestamps = false;
public static $table = "users_metadata";
public static $key = "user_id";
public function city()
{
return static::has_one('City');
}
}
error
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'profile_id' in 'where clause'
SQL: SELECT * FROM `cities` WHERE `profile_id` = ? LIMIT 1
Bindings: array (
0 => 1,
)
If i dont pass the id to has one i get the following error
Okay i understand this.
So my questions is am i able to pass the foreign key cities_id somehow in my relation to match? Or im doing it all wrong? Can someone give me a basic example?
thank you folks
Try this:
City model
class City extends Eloquent
{
public static $table = "cities";
public function profile()
}
Profile model
class Profile extends Eloquent
{
public static $timestamps = false;
public static $table = "users_metadata";
public static $key = "user_id";
public function city()
{
return static::belongs_to('City');
}
}
I ran into the same problem thinking I should use has_one, but I needed to use belongs_to. user1808639's probably didn't work because you still had a 'has_many' in the city model.
Try this:
class Profile extends Eloquent
{
public function city()
{
return $this->belongs_to('City'); // city_id in the table
}
}
Laravel has a way of detecting foreign keys automatically. So for your database schema... this models should work fine
Try the following
user_id | firt name | last name | city_id | //city not cities
1 | Jonh | Doe | 2 |
-
class Profile extends Eloquent
{
public static $timestamps = false;
public static $table = "users_metadata";
public function city()
{
return $this->has_one('City');
}
}
/
class City extends Eloquent
{
public static $timestamps = false;
public function profiles()
{
return $this->has_many('Profile');
}
}
The table rows shouldn't contain whitespaces. So rename "firt name" | "last name" in "firstname" | "lastname". The SQL-error shows me that you're calling the model in the reverse way like City::find(1) in this case Laravel expects inside the "Cities" table the foreign key for the profiles that would be usually "profile_id".
I guess you're looking for something like this:
$user_id = 1;
$user = Profile::find($user_id);
echo $user->firstname." ".$user->lastname." lives in ".$user->city->city;