I have two migration tables and two models
1)User.
2)Subscription.
in subscriptions Model i write one method called user() which has hasMany relationship and in Users model it will contain subscriptions() method which have belongs() relationship.
in user table id acts as an primary key and in subscription table sub_id acts as a foriegn key,for example if the user subscribed to any subscription the user id will store in the sub_id in the subscription table upto this it's working fine.
$is_subscription=Subscription::where('sub_id',$user->id)->value('sub_id');
from the above code i am able to get the value but now what i want is is there any better way to write the query based on models ,please help me to write this one..
According to your descriptions, I believe this is what you have:
class User extends Model
{
public function subscriptions()
{
return $this->hasMany(Subscription::class);
}
}
class Subscription extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
}
So you want to check whether an user has any subscriptions. You can do one of the followings:
$user->subscriptions()->exists();
// Or
$user->subscriptions->isNotEmpty();
You can use pluck() method:
$is_subscription=Subscription::where('sub_id',$user->id)->pluck('sub_id');
You can find details on the methods that are available for collection using the Laravel Documentation
Related
Visit Model
id
user_id
visit_date
public function user()
{
return $this->belongsTo(USER::class,'user_id','user_id')->withTrashed();
}
User Model
user_id
branch_id
name
public function branch()
{
return $this->belongsTo(BRANCH::class,'branch_id','branch_id')->withTrashed();
}
Branch Model
branch_id
branch_desc
I want to display branch_desc when getting list of Visit.
Currently Im showing only branch_id from User Model
You need to make one to Many relation from visit to user table and user to branch table
ex. of relationship code:
//From Visit to User model
$this->belongsTo(User::class, 'user_id')
//From User to Branch Model
$this-belongsTo(Branch::clas, 'branch_id')
This will allow you to eager load the relationships in you controller like this
Visit::with(['user.branch'])
//Now you will get all visits with neseted users and branch
I will recommend you to take a look at laravel relationships docs for a better understanding
Laravel Relationships with eager loading
For 2 layers (or more) relationships, I recommend you install this package from Staudenmeir https://github.com/staudenmeir/eloquent-has-many-deep
Inside your Visit model, you can add the relationship like this:
public function branches() {
$query-> hasManyThrough(Branch::class, User::class);
}
And for more information , check LaravelDaily tutorial related to this package https://youtu.be/wgdWokrm3Mw
Your question isn't clear really! However from what I understand from your question you should also have a Branch model and migration.
So, from visit table you will fetch the users by the relation with user in your visit model.
public function user()
{
return $this->belongsTo(User::class, 'id', 'user_id');
}
Then when you can fetch your user branches from your User model by your users relation with Branch.
public function branch()
{
return $this->hasMany(Branch::class, 'user_id', 'id');
}
So, you will fetch data like this:
$visit->user->branch->description
You can replace description with any column_name_that_wish_to_fetch.
If figured it out.
Use this in getting list of your model in Controller.
This is how to query with multiple relationship
$visit= VISIT::with('USER.BRANCH')->orderBy('user_id','desc');
In my app, you can create lists of roles that are attached to contacts. So you can assign the contact "Bob" the roles of "Gardener" and "Pet Sitter". Then you can create the list "People" and add "Gardener (Bob)" and "Pet Sitter (Bob)" to it.
I have the following tables:
contacts
id
name
roles
id
name
contact_role (pivot)
id
contact_id
role_id
lists
id
name
contact_role_list (pivot)
id
contact_role_id
list_id
Everything was working smoothly until the second pivot table linked to the first pivot table. My pivot tables are (currently) not having any models so I'm not sure if there is a built-in feature to tackle this in Laravel or if I need to think differently.
I currently have this in my List model:
public function list_roles(): BelongsToMany
{
return $this->belongsToMany(XYZ::class, 'contact_role_list', 'list_id', 'contact_role_id');
}
Is this even close? What do I put where it says XYZ::class?
Ok, so the below is doing what I want, but is there an even better way to do it? The key to solving my problem was to create a Model for ContactRole and changing extends Model to extends Pivot.
I placed this in my List Model:
public function list_roles(): BelongsToMany
{
return $this->belongsToMany(ContactRole::class, 'contact_role_list', 'list_id', 'contact_role_id');
}
And this in my ContactRole Model:
public function contact(): BelongsTo
{
return $this->belongsTo(Contact::class);
}
Now I could reach the contact data by using something like this: List::first()->contact_roles->first()->contact
Any way to use with, pivot or similar to tidy this up even more? Thanks!
I like to approach these issues in terms of Models rather than pivots. I think many new Developers in Laravel get over obsessed with what's going on in the Database which is fine, but theres a lot of Magic going on so you can write very simple code that does a lot of Heavy lifting, so that being said if I fully understand your problem
You have a Contacts Model
This model can have many roles
so in your contacts Model you need a role relationship
public function roles()
{
return $this->belongsToMany(Roles::class);
}
next of course you have a role Model (pun intended)
your each role can have many list
public function lists()
{
return $this->hasMany(List::class)
}
then the idea is now that you have roles on contacts and lists on roles you should be able to have many lists through contact
public function lists()
{
return $this->hasManyThrough(List::class, Role::class);
}
I've done similar things before and for your description it seems like that's the approach you might need to take.
I have a User model and workLOG model. The user model has many work logs, meaning One user can have many work logs (ONE TO MANY RELATIONSHIP). I have created a relationship using the Eloquent relationship.
User Model
public function workLog()
{
return $this->hasMany('App\WorkLog','user_id','id');
}
workLog Model
class WorkLog extends Model
{
protected $table="worklog";
}
The worklog table has a column called total_hours_per_day. How can I pull the last N records from the column of the logged-in or authenticated user?
What I have done to get workLog so far
$worklogs = Auth::user()->workLog;
Now I want to get last 7 data from the column total_hours_per_day
Screenshots of the table
you need to establish on the WorkLog model a belongsTo.
public function user()
{
return $this->belongsTo('App\User');
}
Edit: relationships have to be established in both models you're trying to relate. If you like a girl, she needs to like you back to establish a relationship. You just defined the relationship in one side.
Try using take()
As Laravel documentation says:
"The take method returns a new collection with the specified number of items"
$worklogs = Auth::user()->workLog->take(-7)->reverse();
and I pull the last 7 records from total_hours_per_daycolumn in the blade template as:-
#foreach ($worklogs as $worklog)
{{ $worklog->total_hours_per_day }}
#endforeach
Hello i am trying to get one user with his relationships. So one user form user table could have many items, so relationship is one to many.
Booth model
public function booths() {
return $this->hasMany('App\Booth');
}
User model
public function users() {
return $this->belongsTo('App\User');
}
I set foreign key from Booths table user_id is connected with Id from User table.
I try this query
$booth =User::findOrFail(83)->booths()->get();
But get all users. Also tried with with() but in that case i get all booths.
Change your code to
$user = User::with('booths')->findOrFail(83);
So, I've been trying to watch and read eloquent relationships from laracasts. Unfortunately I still don't quite get how to translate database relationships to eloquent relationships (hasOne, belongsTo, hasMany, etc).
Let's say I have an Account and Customer tables. Account table has a "Customer_id" foreign key which references to the "id" on Customer table. Let's assume it's a one-to-many relationship. How should I put it on my models on laravel?
Which table should contain the "hasMany" and which one should have the "belongsTo"?
Just think about how you would say it. In your case it sounds like a Customer has many Accounts and an Account belongs to one Customer.
So you would put the hasMany() in your Customer model and the belongsTo() in your Account model.
class Customer extends Model {
public function accounts() {
return $this->hasMany('App\Account');
}
}
class Account extends Model {
public function customer() {
return $this->belongsTo('App\Customer');
}
}
You can read more about Laravel database relationships here.