I’m building like Twitter to learn Laravel.
I want to get the information of Tweets which I follow, and including my Tweets with 1 query.
This is the model of relationships.
Please check, I only take the information about relationships.
Please give me advice.
Follow Model
class Follow extends Model {
Public function user(){
return $this->belongsTo(User::class, "followed_user_id", "id");
}}
Tweet Model
class Tweet extends Model {
Public function user(){
return $this->belongsTo(User::class, "user_id");
}}
User Model
class User extends Model{
Public function tweet(){
return $this->hasMany(Tweet::class);
}
Public function followUsers(){
return $this->hasMany(Follow::class, "follow_user_id");
}
Public function followedUsers(){
return $this->hasMany(Follow::class, "followed_user_id");
}}
If you want to get all the users with his all the tweets you can simply use
User::with('tweets')->get();
If you want to get the tweets of a single user in a single query you can
User::with(['tweets' => function($query) use ($userId){
$query->where('user_id', $userId);
}])->first()
Related
I am trying to keep a relationship between two tables in my database.
Users Table:
Id User_id Name
Contacts Table:
Id User_Id contacts
I am saving multiple contacts in the contacts table. Now i want to retrieve all the contacts saved to the User_ID. For that, i am trying to establish a hasOne relationship but i get a error for the following code can someone let me know what i am doing wrong? I am following the official documentation for this.
User model:
class users extends Model
{
protected $table = "users";
public function contacts()
{
return $this->hasOne('App\contacts','User_Id');
}
}
Contacts Model:
class contacts extends Model
{
public $table = "contacts";
public function Users(){
return $this->belongsTo('App\Users','User_id');
}
}
Controller:
public function eloquentget(){
$contacts = Users::find(1)->contacts->first();
return response()->json($contacts,200);
}
When i try this code in postman i get an Exception :
ErrorException
Trying to get property of non-object
What am i doing wrong? Any help will be appreciated.
Since you are saving multiple Contacts for any given User then you are using the wrong relation. You need to setup a One-Many relationship using hasMany().
class users extends Model
{
protected $table = "users";
public function contacts()
{
return $this->hasMany('App\contacts','User_Id','User_Id');
}
}
Try something like this
class users extends Model
{
protected $table = "users";
public function contacts()
{
return $this->hasMany('App\contacts','User_Id','User_Id');
}
}
And on your controller, You can use it like this
$contacts= User::find(1)->contacts; // it will return an array of collection
You don't need to use ->first(); because you already used relation hasOne
just use :
$contacts = Users::find(1)->contacts;
return response()->json($contacts,200);
My data model is this:
Users > Offices > Organization
This is my model
class Organization extends Model {
protected $table = 'organizations';
public function offices()
{
return $this->hasMany('App\Models\Office');
}
public function users()
{
return $this->offices()->users();
}
....
So.. I want to get all users from an organization (of all the offices).
But I don't know how to do something like
$this->offices()->users();
(Avoiding user a manual collection or map to do that)
Thanks!
So, you have organization ID. You can load all users by using whereHas():
$users = User::whereHas('office', function ($q) use ($organizationId) {
$q->where('organization_id', $organizationId);
})
->get();
Make sure office() relationship is defined correctly in User model:
public function office()
{
return $this->belongsTo('App\Office');
}
Alternatively, you could define hasManyThrough() relationship:
public function users()
{
return $this->hasManyThrough('App\Office', 'App\User');
}
And use it:
$organization->users()
I have a many to many relationship between Lists and Users.
This is the List Model:
class ListModel extends Model
{
protected $table = "lists";
public function users()
{
return $this->belongsToMany('App\Models\User', 'list_user', 'list_id', 'user_id')->withTimestamps();
}
}
This is the User model:
class User extends Authenticatable
{
public function lists()
{
return $this->hasMany('App\Models\ListModel');
}
}
In a list page, I need to get all the lists belonging to the logged user. The only solution I found is this one:
$user = \Auth::user()->id;
$all_lists = ListModel::whereHas('users', function ($query) use ($user) {
$query->where('user_id', $user);
})->active()->get();
is there any simpler way to achieve the same result?
Since current user is already loaded, you can use lazy eager loading to load lists for the user:
auth()->user()->load('lists');
Your lists() relationship is not defined correctly. The inverse of belongsToMany is still belongsToMany (hasMany's inverse is belongsTo):
class User extends Authenticatable
{
public function lists()
{
return $this->belongsToMany('App\Models\ListModel', 'list_user', 'user_id', 'list_id')->withTimestamps();
}
}
Then you can get the lists like this:
$user = \Auth::user();
$all_lists = $user->lists()->active()->get()
Guys I'm new to Laravel and I'm trying to find the name of the user that answers a certain question:
$users = User::with('answers')->where('question_id', $request->question_id)->get();
I've tried this but it doesn't work.It seems like he is trying to find the question_id from the User and not from the Answer.
Answer Model
Class Answer extends Model{
public function users()
{
return $this->belongsTo(User::class);
}
}
User Model
Class User extends Authenticatable{
public function answers()
{
return $this->hasMany(Answer::class);
}
}
This is what you need, Constraining Eager Loads.
$users = User::with(['answers' => function ($query) use ($request) {
$query->where('question_id', $request->question_id)
}])->get();
This is not what you asked for but maybe what you need:
$answers = Answer::with('user')->where('question_id', $request->question_id)->get();
hi sorry bit of a newbie here but I am have three tables users, profiles, friends. they all have the user_id fields within them and I want fetch all of the fields in one statement using Eloquent and not DB::statement and doing the table joins.
How can I achieve this?
Try this
use the User class and the with method that laravel has to query model relationships
$user = User::with(['profile', 'friend'])->get();
Ensure your models has the correct relationships as follows:
app/models/User.php
public function friend () {
return $this->hasMany('Friend');
}
public function profile () {
return $this->hasOne('Profile');
}
app/models/Profile.php
public function user() {
return $this->belongsTo('User');
}
app/models/Friend.php
public function user() {
return $this->belongsTo('User');
}
use some thing like this:
You should define relations in your models with hasOne, hasMany.
class Review extends Eloquent {
public function relatedGallery()
{
$this->hasOne('Gallery', 'foreign_id', 'local_id');
}
}
class Gallery extends Eloquent {
public function relatedReviews()
{
$this->hasMany('Review', 'foreign_id', 'local_id');
}
}
$gallery = Gallery::with('relatedReviews')->find($id);
Will bring the object Gallery with
$gallery->id
gallery->name
...
$gallery->relatedReviews // array containing the related Review Objects