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
Related
I'm using Laravel and I'm trying to return this on API:
{
id: 1
name: BOM DIA
},
id: 2
name: BOM DIA (SUPERM VANEZA, BATISTA & IZEPE, BOM DIA)
}
But I'm confused. I have a table named 'Teams', and at this table, some columns have a number 'biid'. This 'biid' is the same information from another table name 'Clients'.
More than one 'Clients' can have same 'biid', but 'Teams' only have unique 'biid' or don't have any 'biid'.
I wanna to concat 'Teams' who has 'biid' with column named 'slug' in table 'Clients'.
Tables:
This should be like this:
How can I even think in make this?
Hello you need relations to do it if i know your problem
so let's talk about relation in your case Teams as many clients
the relation in your model teams will be this:
public function client(){
return $this->belongsToMany(Client::class);
}
What laravel does with belongsToMany method ?
for each client who as the same id's who you references teams and laravel will add it to you Eloquent Object.
Your client has one teams
soin your client model if you named it client :
public function team(){
return $this->belongsTo(Model::class);
}
to get the detail of relation who you need :
you will need to make the relations request, this will contribute to remove n +1 problem:
$clients = Client::with(['team']);
$teams = Team::with(['client']);
// here i don't know if you need ->get() try without and with
To access the relations:
foreach($clients as $client){
echo $client->team->name;
}
foreach($teams->client as $team){
echo $team->name;
}
// or
foreach($teams as $team){
echo $team->client->name;
}
But i think for that you need to rename you column because that are not explicit for laravel
to access relations you column need to have client_id and team_id to work.
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;
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');
}
I am using backpack CRUD package to create my website project in laravel 5.2
I want to establish a relationship between two tables. First table is called customer and second table is called transaction. Each customer has many transaction(1:N relationship).
Customer table record:
ID Name
123456 xyz
Transaction table record:
ID CustomerID
101010 123456
I know that I have to specify the relation in the customer model. But, how can I display the result of the relationship in CRUD ?
You should have relationships on both the Transaction and the Customer models, so you can do $customer->transactions and $transaction->customer:
class Customer extends Model
{
/**
* Get the comments for the blog post.
*/
public function transactions()
{
return $this->hasMany('App\Transactions', 'CustomerID', 'ID');
}
}
and
class Transaction extends Model
{
/**
* Get the comments for the blog post.
*/
public function customer()
{
return $this->belongsTo('App\Customer', 'CustomerID', 'ID');
}
}
Spend some time in the Eloquent Relationships Documentation. It's really important to understand them if you want to be a Laravel developer.
In order to display the relationship in the CRUD, you can then use Backpack's select column type to display it in the table view and select or select2 field types to display it in the add/edit views. Read the CRUD Example Entity to better understand how that works.
First of all when you are creating migrations for both tables, table which contain Foreign Key (FK) must have field like this:
public function up(){
$table->increments('id');
$table->integer('customerID')->unsigned();
}
After that you are need to call next command into console
php artisan migrate
Next is going next commands:
php arisan backpack:crud customers
php arisan backpack:crud transactions
After that you need to define functions in models which returns values from other tables. Customer models need to have next function
public function transactions(){
return $this->hasMany('Transaction');
}
Transaction model must have next function
public function customer() {
return $this->belongsTo('Customer');
}
Next you must add CRUD field in Customer controller to display
transactions in select box.
$this->crud->addField([
'label' => 'Transactions', // Label for HTML form field
'type' => 'select2', // HTML element which displaying transactions
'name' => 'customerID', // Table column which is FK for Customer table
'entity'=> 'customer', // Function (method) in Customer model which return transactions
'attribute' => 'ID', // Column which user see in select box
'model' => 'Transaction' // Model which contain FK
]);
Hope this helps :)
After you built onetomany relationship with transaction, you can get the results.
$customer=Customer::where(['id'=>'123456'])->with('transaction')
->first();
print_r($customer->Name); // gives the customer name
foreach($customer->transaction as $cid)
{
print_r($cid->CustomerID); // gives the customer id
}
Laravel Relationships Documentation is always helpful. Go through it.
I am trying to set up a relationship in Laravel using the eloquent relationship model, it looks like the one below
users
id
email
projects
id
name
user_projects
user_id
project_id
role
I want to be able to query the projects that the user is a part of irrespective of the role that he has. To do this, I used the following in my user model.
class User extends Model {
public function allProjects() {
return $this->belongsToMany('App\ProjectRoles', 'user_projects', 'user_id', 'project_id');
}
}
But because of this I get an error in my code
Syntax error or access violation: 1066 Not unique table/alias: 'user_projects' (SQL: select `user_projects`.*, `user_projects`.`user_id` as `pivot_user_id`, `user_projects`.`project_id` as `pivot_project_id` from `user_projects` inner join `user_projects` on `user_projects`.`id` = `user_projects`.`project_id` where `user_projects`.`user_id` = 2)
I am not sure how to create the join query in the relationships in order to do it. Any help would be appreciated. I went through the eloquent docs but wasn't able to get the result even though the examples there do exactly what I want.
Your belongsToMany relationship is related to the wrong Model. Generally you don't have a model for your pivot table, but even if you do, your belongsToMany relationship doesn't use it. Your User model should be related to your Project model.
You should use this:
class User extends Model {
public function allProjects() {
return $this->belongsToMany('App\Project', 'user_projects', 'user_id', 'project_id');
}
}