I've got a strange problem.
I've a users table and a company table. A User belongsTo a company and a company hasMany users.
Both primary keys of the table are id.
In the laravel documentation I read the following:
Additionally, Eloquent assumes that the foreign key should have a
value matching the id column of the parent.
I've got this in my CompanyModel:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class);
}
When I try this:
$users = CompanyModel::find(1)->users;
dd($users);
It's not working. When I add a foreign key in my relation it works!?:
protected $table = 'company';
public function users()
{
return $this->hasMany(UserModel::class, 'id');
}
This is strange right? What on earth am I doing wrong.
--EDIT--
In my users table I've got a company_id column!
Firstly, I would suggest you rename your Model from CompanyModelto Company and from UserModel to User.
Then ensure you have company_id in your users table. And in your users migration file connect the users table with the companies table as such:
$table->integer('company_id')->unsigned();
$table->foreign('company_id')->references('id')->on('companies')->onDelete('cascade');
Don't forget to refresh your database.
Then in your models, define the relationships as such:
// User model
// Laravel will automatically identify and use the `company_id` field in your reference
public function company(){
return $this->belongsTo(Company::class);
}
// Company model
public function users(){
return $this->hasMany(User::class);
}
You can then fetch your records in your controller as such:
$user = User::find(1);
$user_company = $user->company; // This might not be necessary in your controller, you can do it in your view
dd($users, $user_company);
Related
I am want to update my records in my database using Eloquent model. I am having an error in updating user_profile table that saying where id is not null.
User Model
class User extends Model
{
public function profile()
{
return $this->hasOne('App\Models\Common\UserProfile');
}
}
UserProfile Model
class UserProfile extends Model
{
public function user()
{
return $this->belongsTo('\App\Models\User');
}
}
Controller
$user->fill($data);
$user->save();
$user->profile->fill($data);
$user->profile->save();
In MySQL query it looks like this:
UPDATE users, user_profiles
SET users.name='Test Name',
user_profiles.email='test#gmail.com'
WHERE users.id=1
AND user_profiles.user_id=1;
I know MySQL query but I'm new to Eloquent and I want to do it in Eloquent model. Maybe there are some in here that can provide an explanation on how the magic works in Eloquent.
By default eloquent assumes, that any model has an id column as primary key. If that is not the case, you need to "register" the primary key with
protected $primaryKey = 'user_id';
in the model class.
I want to know how to make relationship using laravel Model & Eloquent.
I have data structur something like this
UserTable
username
groups
id
GroupTable
id
name
remark
My question is how to display user groups (user can assign to many groups)
and how to count how many users that assigned to each group.
thanks.
Update
public function store(Request $request){
$member = new Member();
$member->username = $request->input('name');
$member->gender = $request->input('gender');
$member->joindate = $request->input('joindate');
$member->remarks = $request->input('remarks');
if ($request->hasFile('photo')) {
if ($request->file('photo')->isValid()) {
$path = $this->upload($request);
}
}
$member->save();
foreach ($request->only('groups[]') as $key => $group){
$pivot = new pivot();
$pivot->user_id = ????? //how to get user id?
}
}
public function upload(Request $request)
{
$path = $request->file('photo')->store('profile');
return $path;
}
is that right?
and how to get currently saved user_id (it has auto increment column).
You will need to create a pivot table assigning each user to their respective groups.
so basically your tables would be like:
User Table
id
username
Groups Table
id
name
remark
User -> Group Pivot Table
user_id
group_id
Then you can use an Eloquent relationship on your user model to define your relational method like so:
class User extends Model {
public function groups() {
return $this->belongsToMany(Group::class, 'user_group_pivot_table_name', 'user_id', 'group_id');
}
}
Finally, you can return a collection of all the user’s groups by doing the following:
$user->groups();
The Laravel documentation on the Eloquent ORM is phenomenal too. Happy hunting.
i have two tables as below:
users table:
|id|name|email|password|created_at|updated_at
messages table:
|id|sender_id|receiver_id|message|created_at|updated_at
User model:
public function threads()
{
return $this->hasManyThrough(Message::class, User::class,'id','sender_id');
}
i'm trying retrieve message threads
which isn't working. any help appreciated.
This is an example from laravel eloquent relationship
class Country extends Model
{
public function posts()
{
return $this->hasManyThrough(
'App\Post',
'App\User',
'country_id', // Foreign key on users table...
'user_id', // Foreign key on posts table...
'id', // Local key on countries table...
'id' // Local key on users table...
);
}
}
can you review your code
It seems that you want to retrieve all messages that belongs to a single thread (list of users) using hasMany relationship Through User model, to do that You have to define hasManyThrough inside Thread model not in User model, here is an example:
User:
|id|name|email|password|created_at|updated_at|thread_id
Note thread_id foreign key because thread is a list of users
Thread:
class Thread extends Model {
public function messages() {
return $this->hasManyThrough(Message::class, User::class,'thread_id','sender_id', 'id', 'id');
}
}
Example from laravel doc
I have two models (see below). With a one to many relationship, the HasMany relationship is working as expected, but the inverse belongsTo doesn't get any results when I try to do this.
$user = Auth::user();
dd($user->location->name);
I have the following database structure
Table locations
id
name
slug
Table users
id
name
email
password
location_id
remember_token
App/User model
public function location() {
return $this->belongsTo( 'App\Models\Location' );
}
and the App\Models\Location model
public function users()
{
return $this->hasMany('App\User');
}
I am trying to create a youtube style subscription model for my application. I've had small amounts of success so far, that being that you can follow other users and it stores who is following who in the database. However I am having trouble retrieving the list of people the current user is following.
The database:
users table (id, first_name, last_name, email, password, token, timestamps)
subscriptions Table (id, user_id, subscriber_id, timestamps)
user model:
public function subscriptions()
{
return $this->belongsToMany('App\User', 'subscriptions', 'user_id',
'subscriber_id')->withTimestamps();
}
public function subscribers()
{
return $this->belongsToMany('App\User', 'subscriptions', 'subscriber_id',
'user_id')->withTimestamps();
}
I am using this code to retrieve all of the current users subscriptions (aka who they are following)
$subscriber = Auth::user()->id;
$user = User::find($subscriber);
$userids = $user->subscriptions->lists('user_id');
return $userids;
Now, this code is currently returning a null value. On further investigation this makes sense as the query that is being run is incorrect
SQL Query:
select `user_id` from `users` inner join `subscriptions` on `users`.`id` = `subscriptions`.`subscriber_id` where `subscriptions`.`user_id` = 14
My current set up is trying to look for the wrong thing.
If user 1 follows users 2, 3 and 4 then my code should return 2, 3 and 4.
Can somebody please help correct my relationship set up or the code that I am running? It should be looking for the user_id in the subscriptions table based on the current users subscriber_ID.
Laravel 5.3 Eloquent Relationships
If you check the code at the end of the Many-to-Many relationships part, you will see this line of code.
return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
Here, we have the 'role_user' as the pivot (relationship) table, 'user_id' which is the foreign key in relationship table and primary key in user model, and 'role_id' is foreign key in relationship table and primary key in roles model.
So when you try to do this:
public function subscriptions()
{
return $this->belongsToMany('App\User', 'subscriptions', 'user_id',
'subscriber_id')->withTimestamps();
}
You are actually taking 'subscriber_id' as a foreign key in your relationship table and primary key for a subscriber. Since the function is trying to get the subscriptions, reaching to the subscriber id's won't do the work. This is why when you changed them they worked.
The result should look like this:
public function subscribers()
{
return $this->belongsToMany('App\User', 'subscriptions', 'user_id',
'subscriber_id')->withTimestamps();
}
public function subscriptions()
{
return $this->belongsToMany('App\User', 'subscriptions', 'subscriber_id',
'user_id')->withTimestamps();
}
So out of pure chance, I swapped the subscribers() and subscriptions() relationships about and it's now returning the correct data.. I don't understand why but it is definitely returning the ID's that I was expecting.
I'll keep the question open for now in case anyone with a clear solution answers.