I have 2 tables. (1) being users, and (2) being foods.
In the [users] table, there is a food_id bracket that is linked as a foreign key to an item/column's id in the other table [foods]. I want to be able to go fetch data in that other column, via my user_id link in my [users] table.
I don't know how I am supposed to do this, despite reading the documentation, I am very beginner at this and it is part of my assignment. I've tried a few possible solutions, only to fail.
I have a controller, in which I refer the function into a view, that will display the food item/column related to the current logged user, with an if statement verifying if a certain data is present in order to display the HTML block object.
public function browseReserved()
{
//
$user = User::find(auth()->user());
$foodId = $user->where('food_id')->id;
}
So, how do I go fetch data from an item located in another table, from a data key that is linked to the id of said item?
add relationship in user model
public function food(){
return $this->belongsTo(Food::class);
}
then in controller
public function browseReserved()
{
$user = User::with('food')->find(auth()->id());
dd($user->food);
}
same like #john lobo answer but u can add foreign key on user model
public function food(){
return $this->belongsTo(Food::class,'food_id');
}
Related
I'm trying to use a function to soft delete 2 rows in a database, one is from a table I made called persona and the other one is from the users table that laravel makes with Auth, My users table have a foreign key associated to the persona table called idPersona. What I'm trying to do is to soft delete the row from the persona table that matches the id parameter and after that soft delete the row in users where the attribute idPersona matches the id parameter that the function recieved.
I'm going to post the Controller function code
Controller function code
public function deleteMedico($id){
$medico = Persona::findOrFail($id);
$medico->estado =False;
$personaID = $medico->id;
$user= new User();
$user->where('idPersona',$personaID);
var_dump($user);
}
I'm going to try to explain what I'm trying to do with this controller, I use the findOrFail function to find the row I'm trying to self delete from the persona table, after I found it I set estado to false in this way soft deleting the row. After that I try to get an User instance, look for the users table where idPersona matches the id of the row that was soft deleted.
The code for self deleting it would be almost the same than with the persona table but the problem is I can't find the row in the users table, gonna post the var_dump I get of $user.
Also gonna post how my database looks in case it is useful
I have no idea what I need to do to get the row of the users table where the idPersona attribute matches the id attribute from the personas table. I'm new in Laravel so sorry if this question is repetitive or is nothing to hard. p
Your syntax is wrong.
// $user = new User();
// $user->where('idPersona',$personaID);
$user = User::where('idPersona', $personaID)->firstOrFail();
This should fix the syntax but there are simpler ways to do this in your code.
Route model binding
Route::get('deleteMedico/{persona}', ...);
Eloquent Relationships
// Persona.php
public function user()
{
return $this->hasOne(User::class, 'idPersona');
}
public function deleteMedico(Persona $persona)
{
$persona->fill(['estado' => false])->save();
$persona->user->fill(['estado' => false])->save();
}
You forgot the get method.
User::where('idPersona',$personaID)->get();
So here's how this is set up.
A Step has a Category
A Category has a Section
A Section has Multiple Questions
I thought I had everything working in my model files, but unfortunately I'm running into an integrity error with my foreign keys.
My models are named:
Step.php
StepCategory.php
StepSection.php
StepQuestion.php
I'm not really sure how to set up my "many to one" relationships, or what belongs to what.
My database table names are as follows:
steps
step_categories
step_sections
step_questions
I'm running into this error when i'm deleting the parent entry of anything... If i delete a step, it should delete a category, the sections, and the questions associated with them. If i delete a category, it should delete the section and questions. If i delete a section it deletes all the questions.
In my step_categories table i have the foreign key column named as step_id.
In my step_sections table i have the foreign key column named as category_id.
In my step_questions table i have the foreign key column named section_id.
My foreign key name on my step_categories table is step_categories_step_id_foreign.
My foreign key name on my step_sections table is step_sections_category_id_foreign.
My foreign key name on my step_questions table is not set up yet as I have yet to make that part of the site yet. I'm currently stuck on the sections portion.
My destroy() function in my StepsController.php file is:
public function destroy($id)
{
// Find the step by the ID
$step = Step::find($id);
// Find all the categories and delete them.
$step->category()->delete();
// Delete the step
$step->delete();
// Flash the Session
Session::flash('success', 'The step has been successfully deleted.');
// Return Redirect to the index page
return redirect()->route('steps.index');
}
Heres how my models look so far... This is as far as I've gotten... :(
Step.php
class Step extends Model
{
// Tell the model what table to use
protected $table = 'steps';
// Define the relationship between steps and step categories
public function category() {
return $this->hasMany('App\StepCategory');
}
}
StepCategory.php
class StepCategory extends Model
{
// Tell the model what table to use
protected $table = 'step_categories';
// Define the relationship between step categories and steps
public function step() {
return $this->hasOne('App\Step', 'id', 'step_id');
}
// Define the relationship between steps categories and sections
public function section() {
return $this->hasMany('App\StepSection');
}
}
and my StepSection.php
class StepSection extends Model
{
// Tell the model what table to use
protected $table = 'step_sections';
// Define the relationship between step sections and step categories
public function category() {
return $this->hasOne('App\StepCategory', 'id', 'category_id');
}
}
So thats legit as much information as I can possibly give that I think will solve the problem. If you need anymore information to help me set up these relationships let me know.
So far I can delete a Step, and it will delete the category, so long as the category has no sections attached to it. However I can't delete the Step, or Category if it has any sections attached to it. :/ Don't know whats going on.
It looks like your problem is because of your tables, so make sure that when you declare a foreign key in your migrations you are adding what should be done on delete/update of those rows. For example:
On your step_categories the foreign key 'step_id' should be like this:
$table->foreign('step_id')->references('id')->on('step')->onDelete('cascade')->onUpdate('cascade');
You should do the same following with all your tables
What I'm trying to do is to show the posts that have been saved by the user in the profile. I will try to explain it as good as possible refering to my code. So:
public function userProfil($id)
I have the profile function which get the data from userprofile table. and inside I have the following code for saved data:
$authed = User::find($id);
$savedarticles = $authed->mysaves;
$allsavings = DB::select("Select * from article where id=$savedarticles->id");
But this code does not work like this anyway. I can do this instead:
$authed = User::find($id);
$savedarticles = $authed->mysaves;
But when I try to get articles from article table with the article_id of mysaves, it does not work such as this:
$allsaved= DB::table('article')->where('id', $savedarticles->article_id);
the error it gives is like:
Property [article_id] does not exist on this collection instance.
although savearticle table has article_id I can output it without the line above and in view I get them as:
#foreach($savedarticles as $savedarticle)
<p>{{$savedarticle}}</p>
#endforeach
it gives me everything that is in the savearticle table and I can get do savedarticle->article_id and get article_id but can't get it in controller.
I am using Laravel 5.4.
The error message Property [article_id] does not exist on this collection instance. means you are trying to get an attribute of a single instance but from a collection.
For example the collection could be like
[$article1, $article2, $article3]
therefore what you tried to do is something similar to
[$article1, $article2, $article3]->article_id
You are trying to get an attribute from a collection instead of a single instance.
As for your query, you can use where in sql statement to search for rows that match any item in an array
$allsaved= DB::table('article')->whereIn('id', $savedarticles->pluck('article_id')->all());
What I have understood is that A USER has many POSTS and a POST belong to an article.
If this is true then you have to do following.
1: In USER model define a relation to get all posts. like below.
public function posts() {
// Foreign key will be a key that is stored in posts table and represent the user MAY BE: user_id
$this->hasMany(Posts::class, 'foreign_key', 'local_key')
}
This will allow you to get all posts belong to a user.
2: In posts, model defines a user relation like below.
public function user() {
$this->belongsTo(User::class, 'foreign_key', 'local_key');
}
This will allow you to get a post User;
3: Now in your controller you will have something like this.
public function show($user_id) {
// find a user with posts as eager loading(to avoid query again)
$user = User::with(['posts'])->where('id', $user_id)->first();
// get all posts that belong to this user
$posts = $user->posts;
}
In controller show($user_id) method you will have a user data as well as user posts data. Now if you want to get a post relations then simply define as below. let say a post belongs to an article as well.
4: In posts, model defines a relation to get an article.
public function article() {
// This will allow you to get a post artcle
$this->belongsTo(Article::class, 'foreign_key', 'local_key');
}
Now you can get the article as well while finding a user. please see below. I am rewriting controller show action to give you a better understanding.
5: Get a user with user_id
public function show($user_id) {
// find a user with posts as eager loading(to avoid query again)
// eager loading for posts & post child, this will give you NOSQL at runtime and all data will come from one query.
$user = User::with(['posts', 'posts.article'])->where('id', $user_id)->first();
// get all posts that belong to this user
$posts = $user->posts;
foreach($posts as $post) {
$article = $post->article; // Child relation of post.
}
}
Hope you will understand the flow, you have to make sure models relation to work it perfectly. If you need further help please let me know.
I am trying to figure out a relationship but I can't seem to solve the issue.
So what my script does first is checking if there is a valid session where status = 0.
Then I want to check if there is a valid trial where status = 0 ->first() associated with that session. And if so, I want to grab all the relevant data related by trial_id.
I understand what logic is required. However, I am wondering if there is a method to do this with as little commands as possible using Eloquent relationships.
Specifically, once i have the $session object. How can I filter the trials, in order to get the appropriate stimuli_tracker data?
The important components to the relationships for the table is as follows:
Sessions
id (has one to many relationship to trials(sessions_id)
user_id (foreign key)
status
Trials
id (one to many relationship with stimuli_tracker)
sessions_id (foreign key)
status
Stimuli_Tracker
trials_id (foreign key)
stimulus
stimulus_type
Sessions Model
class Sessions extends Model
{
protected $table = 'sessions';
public function stimuliTracker()
{
return $this->hasManyThrough('App\StimuliTracker', 'App\Trials', 'sessions_id','trials_id');
}
}
Trials Model:
class Trials extends Model
{
public function stimuli()
{
return $this->hasMany(App\StimuliTracker);
}
}
EDIT
I have tried in artisan tinker to
$object = \App\Session::where(arg);
then I tried to
$object->stimulus
but didn't work. I tried a few other fields but I only received null. Maybe I'm not getting how to grab the content properly
$object->stimulus is an undefined attribute based on what you've shown in your code.
To access the stimulus information for your session, you have to use the name of the relationship, which in this case is:
$object->stimuliTracker
The thing is that this will return an Eloquent Collection because it is a hasManyThrough relationship (which is a hasMany of a hasMany).
I'm assuming that the 'stimulus' attribute belongs to the StimuliTracker class. If this is the case, then you will need to loop through your StimuliTracker Collection to extract it:
foreach ( $object->stimuliTracker as $record )
{
$stimulus = $record->stimulus;
// do something with $stimulus
}
EDIT (Added):
If you are just looking for an array of the values in the 'stimulus' attribute, you can get that with the lists() method:
$stimulus_values = $object->stimuliTracker->lists('stimulus');
I am trying to make a twitter like feed in an application, I have a database called connections where inside there's user and follow and another database called feed containing owner which would equal to the follow column in connections.
What I could do if had every id of a follower statically is to use where('owner', '=' $follow) on each follower and return it.
I tried this approach but it wasn't ideal:
Get each follower inside connections;
foreach(follower) {
Get 10 of the latest posts orderBy "created_at";
Push into array;
}
shuffle array;
limit array to 15;
return array;
That also ended with the returned array not being ordered by created date.
How would I use eloquent to get the feed item only if the user follows the owner in the best/simplest way?
Are there any specific Laravel tools that can be used?
Also the database layout isn't fixed as it is, it can be altered if needed to better suite this.
You need to create a many-to-many relationship between the user and itself. See the laravel eloquent documentation http://laravel.com/docs/eloquent#relationships. I didn't test this code but it should be enough to get you started down the right track.
Create a pivot table called "user_following" with:
(int) id, (int) user_id, (int) following_id
Then do something like this:
<?php
// Model
class User extends Eloquent {
public function following()
{
return $this->belongsToMany('User', 'user_following', 'user_id', 'following_id');
}
public function tweets()
{
return $this->hasMany('Tweet')->orderBy('created_at', 'desc');
}
}
// controller
$tweetsOfWhoImFollowing = User::find($id)->following->tweets;