Query same table with pivot table - mysql

I have following tables:
users - id, username, etc.
conversations - id, private, etc.
conversation_user - id, user_id, conversation_id
There are two records in the conversation_user table for each open/started conversation (could be more if a conversation is multi user).
One for user as recipient/recipients, another for a user as sender. Let's say: user_id=1, conversation_id=1 and user_id=2, conversation_id=1.
How can I select all users/usernames I have an open conversation with. All the participants, to be exact.
I assume I need to get a conversation id's I'm a participant at and then do a reverse lookup for other users in the conversation. But no luck so far... This reverse lookup is where I got stuck.
I'm playing with Laravel 5.3 and MySQL.

First of all, you need a has_started_conversation kind of boolean on your pivot table, conversation_user.
As noted in the docs, you need to define the relationships between your Conversation and User models.
User
class User extends Model
{
public function conversations()
{
return $this->belongsToMany('App\Conversation')->withPivot('has_started_conversation');
}
}
Conversation
class Conversation extends Model
{
public function users()
{
return $this->belongsToMany('App\User')->withPivot('has_started_conversation');
}
}
Then
// get a users conversations
$conversations = \App\User::first()->conversations;
// select a single conversation, or maybe multiple with a for loop?
$important_conversation = $conversations->random();
// get the participants of that conversation
$participants = $important_conversation->users;

Related

How to join two table in laravel 8 with no duplicate

I have two tables. Customer and address. The relationship of the table is that a CUSTOMER can have many ADDRESSES. So what I want as a result to my query is to get the list of customer and only one latest address
ADDRESS TABLE
id : 1
city:"cebu"
zip_code:"600"
cus_id:1
id:2
city:"mandaue"
zip_code:"6001"
cus_id:1
CUSTOMER TABLE
id: 1
name:"JOHN DOE"
What I want to get the customer "JOHN DOE" and the address with ID "2"
I'm using laravel query builder
If you want to get only one latest address, you can use hasOne same as :
// Customer model relation
public function lastestAddress()
{
return $this->hasOne(Address::class, 'customer_id')->orderBy('id', 'desc');
}
And
$model = Customer::with('lastestAddress')
you can use Eloquent ORM in laravel.
Eloquent :
You must setting in your customer model
Class Customer(){
public function address()
{
return $this->hasMany(Address::class, 'cuss_id', 'id')->latest();
}
in your Adress model :
Class Address(){
public function customer()
{
return $this->belongsTo(Customer::class, 'id', 'cuss_id')
}
Then in your controller you can call the model :
$data = Customer::with('address')->get();
So you have two tables: customers and addresses, with a "one customer can have many addresses" relationship.
In Laravel, we normally use Eloquent models to query the database. So to get a customer and all its addresses, we must first model the database; each table with its own Eloquent model. (See details in the docs.)
class Address extends Model
{
// although empty for now, this class definition is still important
}
class Customer extends Model
{
/**
* Get the latest address.
*/
public function currentAddress()
{
return $this->hasOne(Address::class, 'cus_id')->latestOfMany();
}
}
In the Customer model, our currentAddress() method defines how a Customer instance related to the Address instances.
It's like we're saying,
"A customer may have many Addresses. Just get one which is the latestOfMany. That's how we'll get the customer's currentAddress.
Now that we have the necessary Eloquent models setup, we can lookup John Doe and his current address.
$johnDoeId = 1;
// query the database for customer 1, including its current address
$johnDoe = Customer::with('currentAddress')->find($johnDoeId);
$johnDoe->currentAddress; // 👈 John's latest address, at Mandaue

Laravel 6. Get all users who don't have contacts in one to many relationship

I'm trying to get all the users who don't have contacts. Lets say
my User model
public function contacts(){
return $this->hasMany(Contacts::class);
}
my Contacts model
public function user()
{
return $this->belongsTo(User::class);
}
Expected results:
get all users who don't have contacts yet. for example, if a 4 out of 7 users have contact in contacts table and I want to get rest 3 users (which don't have entry in contacts table)
I tried below code but it is returning all users not only users who don't have contacts
DB::table('users')
->select(
'users.id',
'users.*'
)
->leftjoin('contacts','contacts.user_id','=','users.id')
->whereNull('contacts.user_id')
->get();
my English is not good so pardon grammatical mistakes.
You should use relationship absence
use App\User;
$noContacts = User::doesntHave('contacts')->get();
https://laravel.com/docs/6.x/eloquent-relationships#querying-relationship-absence

Laravel BelongsToMany method returns nothing

I am implementing a many-to-many relationship in Laravel.
The entities are:
users
roles
and pivot table user_role
Users
====
id
name
.....
roles
====
id
role
...
user_role
======
userId
roleId
Trying various ways to get the roles of a user but no luck so far. Any ideas?
Last try is:
/**
* #return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function roles()
{
return $this->belongsToMany(Role::class, 'user_role', 'userId', 'roleId');
}
Current output on Laravel Tinker:
>>> $user->roles()
=> Illuminate\Database\Eloquent\Relations\BelongsToMany {#2380
+withTimestamps: false,
$user->roles() is just the query for the relationship, it is not executed
You can use
$user->roles
if you don't need to add extra conditions or
$user->roles()->where(your conditions)->get()
for a more complex relationship query.
The key difference is the usage of pharentesis: ->roles vs ->roles(). The former returns the query result, the latter the query itself

Laravel 5: User follow another user (like twitter) - how to setup relationship

I have user table .
Relation:
One user can follow more than one user.
How to setup data structure and how to declare relationship in laravel 5.2
Output:
show who are my followers
show my following list ( I follow another user )
create a table followers with these columns: id, user_id, follower_id
2.Create Model like
User Model
public function following(){
return $this->hasMany('App\Follower', 'user_id', 'id');
}
Follower Model
public function following(){
return $this->belongsToMany(User::class, 'followers', 'follower_id', 'user_id');
}

Laravel 5.2 How to get values from two or more table from a relationship

I have a default authentication table user and another table user_profiles
user(id,email,password)
user_profiles(id,first_name,last_name,mobile)
i am connecting these two table using a many-to-many relationship
for this, i added relationship in the both model class- User and UserProfile
// User Model
public function userProfiles()
{
return $this->belongsToMany('App\Models\UserProfile', 'user_user_profile',
'user_profile_id', 'user_id');
}
//UserProfile Model
public function users()
{
return $this->belongsToMany('App\User', 'user_user_profile',
'user_profile_id', 'user_id');
}
and i tried to access the UserProfle details via user table using
$user=\App\User::find(1)->userProfiles()->get();
but not working and also tried
/$user = \App\User::findOrFail(1)->with('userProfiles')->get();
that is also not working , please help to
Get the user_profile table details along with user table
How to access the Pivot table(user_id,user_profile_id) value
How to display these data from multiple tables into a view form?
You have defined the relationship wrong in your User Model: swap user_id and user_profile_id
// User Model
public function userProfiles()
{
return $this->belongsToMany('App\Models\UserProfile', 'user_user_profile',
'user_id' , 'user_profile_id');
}