Very silly situation, The point is I can not change the database architecture because its a running e-commerce business having more then 1m active users.
Here is my situation.
Table User:
Table Store:
Both have same primary key, mean we can call the one to one relation.
But now I have to create belongs to many relation form Store to User.
store table have two columns
slug
parentId
Now I need to get all users having slug of store
So my query is
select * from users where id IN (select id from store where slug = ?);
How can I create a relation in this situation.
Hey there i would try to answer in detail as much as possible.
Create the following relationships:
For store:
public function users(){
return $this->hasMany(User::class, 'id' ,'slug');
}
For user:
public function store(){
return $this->belongsTo(Store::class);
}
Create a new controller and write a new function as below:
public function getStoreUsers(){
$users = Store::where('slug','yourvalue')->firstOrFail()->users;
return response()->json($users);
}
The function above will return a collection of users which have theirs 'id' equals to store 'slug'
In case if you have many stores you can do the follwing:
public function getStoreUsers(){
$stores = Store::all();
$storeUsers;
foreach($stores as $store){
$users = $store->users;
$storeUsers[$store['id']] = array($users);
return response()->json($storeUsers);
}
}
This function will return an array of users of each store.
I have answered according to my understanding of your question if any erros occur please reply below so i can fix if possible. I Hope this is what you wanted if not let me know.
UPDATE:
This is what i could understand from your request.
Store a , store b , store c has slug = xyz.
you have 50,000 users. 10,000 of them has slug xyz. and you need the information of those 10,000 users. if thats the case then the code below will help you out.
public function getStoreUsers(){
$slugtomatch = 'xyz';
$result;
$stores = Store::where('slug',$slugtomatch)->get();
foreach($stores as $store){
$users = $store->users;
$result = array($users);
}
return response()->json($result);
}
This will return an array of users those have the $slugtomatch value in their slug fields.
Related
Database Table Relationship
What I did:
public function index(Request $request)
{
$company_feedback = $request->user()->company()
->get()->pluck('id')- >toArray();
$company = Company::whereIn('id',$company_feedback);
$feedback = $company->feedback;
return view('feedback.index', ['feedbacks' => $feedback]);
}
By using eloquent relationship, how to retrieve feedback data from a specific user id ? I want show feedback data which belong to current login user login id.
anyone could help? show me how to write the code in Index method in Feedback class.
Assuming you have two models User.php and Feedback.php
If you want to retrieve all feedback given by a current user
In your User.php
public function feedback()
{
//assuming you have user_id column in feedback table
return $this->hasMany("App\Feedback",'user_id');
}
In your controller
//all feedback given by the current user
$feedbacks = Auth::user()->feedback;
I want to make query in laravel 5.2 to fetch agencies table which has a foreign key with organizations table using agencies.organization_id=organizations.id. Now Users table has also foreign key with organizations table using users.organization_id=organizations.id. Now how to fetch agency table that which agencies are linked with users_id.
public function postagency(Request $request) {
$user_id = $request->user_id;
$org_id = User::where('id', $user_id)->pluck('organization_id')->first();
$postagencies = agency::where('organization_id', $org_id);
echo $postagencies;
}
For what I understand is that an user can only be under one organisation and an organisation has many agencies. If not please say so and I will alter my answer.
First of all set your relationships inside your models. An example would be:
// User.php
public function organization()
{
return $this->belongsTo('App\Organization'); // App\Organization can be changed depending on the used namespace
}
More info can be found here. If you need some more examples just ask.
After you have created these relationships you can retrieve your agency like this:
$user= User::find($request->user_id);
if (!$user) ... // Check if user exists
$agencies = $user->organisation->agencies;
If I need to explain things in more detail just ask. Hope this helps :)
I think I got a little stuck and I just need someone to clarify things. So what I got is a user system which includes subscriptions for people to "subscribe" to their content (as you already know it from FB, Twitter, YT etc).
My database model looks like this:
Users
id
username
Subsccriptions
id
user_id
sub_id
Currently I have one model for Users and one Model for Subscriptions. The model from the user:
public function subscriptions()
{
return $this->hasMany('App\Subscription');
}
In comparison, my subscription object:
public function user()
{
return $this->belongsTo('App\User');
}
So in my personal opinion this is a 1:many relationship. If I call the user object with User->subscriptions()->get() I can get the subscription and it's sub id, so I know who THE CURRENT user has subscribed.
People told me the opposite and it's supposed to be a many-to-many relationship. Did I do something wrong? Can I automatically convert the sub_id into a user through relationships in Eloquent?
// EDIT:
Here is the current code to receive my subscribers for a user
public function index()
{
$subs = Auth::user()->subscriptions()->get()->all();
$submodels = [];
foreach($subs as $sub) {
array_push($submodels,User::find($sub->sub_id));
}
return view('home', [
'subscriptions' => $submodels
]);
}
}
I am beginner in Laravel Framework.I have searched for my problem and get some solution but those are not solve my problem.So,
profiles table:
I want to need to fill up userID column when any user create a profiles.For this i am trying to code something like this:
Profile model:
public function users(){
return $this->belongsTo('App\User','userID');
}
And User Model:
public function profiles()
{
return $this->hasMany('App\Profile');
}
In this way its keep null value every time.How can i solve this?
Thanks in advanced.
So assuming you have the following (which you kind of do)
public function profiles()
{
return $this->belongsTo(\App\User::class); // we do not need to provide the user_id because laravel assume we are using that
}
<?php
// Profile.php (Model)
public function user()
{
$this->belongsTo(\App\User::class); // Again we do not need to provide the information because of the table / column names we are using
}
You have a few options, you can either when creating the profile, assign the user_id (as long as it is in the fillable fields.
$profile = new Profile;
$profile->user_id = \Auth::getId(); // current logged in user
$profile->somethingElse = 'abc';
$profile->save();
Or since we have a relationship you should be able to do something like this
$profile = new Profile;
$profile->somethingElse = 'abc';
// We will use the current logged in user again
Auth::user()->profiles()->save($profile); // will automagically fill in the user_id with the logged in user's id.
Hopefully that sheds some light
While inserting Data into Profile Table, you just need to do as follows:
$profile = new Profile();
$profile->userID = Auth::user()->id;
$profile->other_columns = 'values'
.....
$profile->save();
There is no need to join the tables for inserting the value in Profile Table for here. Hope this helps you
For example I have:
// Returns all projects
$projects = Projects::all();
To return categories, belonging to project, I use relationships and can do something like:
foreach($projects as $project) { ...show $project->categories... }
I need only specific projects, which are followed by specific user. On my projects_followers table I have user_id and project_id.
To retrieve projects which were followed I have this peace of code:
$projects = Project::rightJoin(DB::raw('(select * from projects_followers group by project_id) projects_followers'),'projects_followers.project_id','=','projects.id')->get();
// Note: This code doesn't include specifuc user_id.
It does retrieve specific rows, but the problem with this code is that laravel relationhips dont work on them. For example $project->categories return empty.
// Relationship
public function categories()
{
return $this->belongsToMany('App\Category');
}
How do I retrieve my model specific rows and make relationships to work?
Actually your question is:
How do I get projects liked/followed by Auth/Logged in User ?
Unfortunately you described it in such a way that it looks something else, anyways. Lets try to find the solution and for this I would like to use something like this:
$projects = Auth::user()->favorite_projects;
So how we can implement this to work, first of all the User Model should contain the method favoriteProjects so lets create it:
public function favoriteProjects()
{
return $this->belongsToMany(
'App\Project',
'projects_followers', // This table already exists as you mentioned
'user_id',
'project_id'
);
}
That's it. You will be able to load the projects followed by the current user and other relationship methods will work on every single project as well.
My workaround:
// I don't know how to create empty collection, so impossible conditions here.
$projects = Project::where('id', 0)->get();
$follows = DB::table('projects_followers')->where('follower_id', Auth::user()->id)->get();
foreach($follows as $follow) {
$project = Project::where('id', $follow->project_id)->first();
$projects = $projects->add($project);
}