admin_roles and admin_permissions table is a many-to-many relationship
Query ID from admin_permission where admin_roles ID in 1,2
Use SQL implementation:
SELECT
DISTINCT`admin_role_permissions`.permission_id
FROM
`admin_permissions`
INNER JOIN `admin_role_permissions` ON `admin_permissions`.`id` =
`admin_role_permissions`.`permission_id`
WHERE
`admin_role_permissions`.`role_id` IN (1, 2)
The result:
$permission_ids = [1,3,4....];
How to use laravel model to the above effect?
AdminRoleController.php
$role_ids = ['1','2'];
$permissions = AdminRole::with('relPermission')->whereIn('id', $role_ids)->get();
AdminRole.php
public function relPermission(){
return $this->belongsToMany('App\Model\AdminPermission', 'admin_role_permissions', 'role_id', 'permission_id');
}
But the result:
How can I obtain a result like
$permission_ids=[1,3,4.....]
use laravel model or laravel collection
You can use the pluck method :
$permissions = AdminRole::with('relPermission')->whereIn('id', $role_ids)->pluck('rel_permission.id');
Related
I have an accessor function for my User model which returns all the conversations of which a User is a participant.
public function getConversationsAttribute()
{
$results = DB::select('SELECT * FROM conversation_user WHERE user_id = ?', [$this->id]);
$conversations = array();
foreach($results as $result){
$conversation = Conversation::find($result->conversation_id);
array_push($conversations, $conversation);
}
return $conversations;
}
Now suppose I have two users $userA and $userB, how can I return the conversations of which both users are participants?
i.e., the common results between $userA->conversations and $userB->conversations
I imagine a UNION operator for duplicates is what is required.
What is the:
MySQL solution
Eloquent solution
Using intersect method of Laravel Collection, you can write
collect($userA->conversations)->intersect($userB->conversations);
I'm trying to select specific columns from tables that I have joined using Eloquent.
I have 3 models
- Transaction
- Channel
- Merchant
Transactions links to Channel. It has a hasOne relationship.
Channel links to Merchant. It also has a hasOne relationship.
public function channel() {
return $this->hasOne(Channel::class, 'uuid', 'entityId');
}
public function merchant() {
return $this->hasOne('App\Merchant', 'uuid', 'sender');
}
I'm using eager loading so have the following in the Transaction model:
protected $with = ['channel'];
And Channel has:
protected $with = ['merchant']:
This the query I'm trying to convert into Eloquent but I'm unsure how to select columns when they belong to related models. What I don't get is that if the relationships have been defined, why can't I select columns from the other models without having to reuse joins or the with clause?
SELECT SUM(t.amount) AS amount,
m.name
FROM transactionsV2 t JOIN
channels c
ON t.entityId = c.uuid JOIN
merchants m
ON c.sender = m.uuid
WHERE t.paymentType = 'DB' AND
t.status = 1 AND
t.processing_time >= '2019-01-01' AND
t.processing_time < '2019-01-21'
GROUP BY m.name;
You could do something like protected $with = ['merchant:id,name']; or maybe use raw expressions like selectRaw('SUM(t.amount) AS amount, m.name)
You can try something like this :
Transaction::sum('amount')
->whereStuf(...)
->with(['channel.merchant' => function($query){
$query->select('name')
->groupBy('name');
}])->get();
The channel.merchant allows you to get the nested relation.
I have SQL query that does that I need:
SELECT users.FirstName, users.Id FROM `orders`
INNER JOIN orderrecipients ON orderrecipients.Orders_Id = orders.Id
INNER JOIN users ON users.Id = orderrecipients.Users_Id;
I try to use Eloquent model to build query above using hasManyThrough:
public function OrderRecipients()
{
return $this->hasManyThrough('App\OrderRecipient', 'App\User', 'Id', 'Orders_Id');
}
And using is:
$recipients = OrderModel::with("OrderRecipients")->where("User_Id", $userId)->get();
dd($recipients->OrderRecipients()->count());
How to build this relation and get data through table?
HasManyThrough is not the best choice here. Use a BelongsToMany relationship instead:
public function OrderRecipients()
{
return $this->belongsToMany('App\User', 'orderrecipients', 'Orders_Id', 'Users_Id');
}
Currently I have three tables one is property table having following columns:
id
name
description
2nd is tags table having following colums:
id
tag_name
tag_status
3rd is the pivot table having following columns:
id
tag_id
property_id
Now in Property Model I have defined the relation with pivot table like this:
public function tags()
{
return $this->belongsToMany('Tag');
}
and in Tag Model I have defined the relation with pivot table like this:
public function properties()
{
return $this->belongsToMany('Property');
}
Now what I need to now is how can I write the following query on these three tables using eloquent ORM of Laravel:
$propertyTags=Property::join('property_tag', 'properties.id', '=', 'property_tag.property_id')
->join('tags', 'tags.id', '=', 'property_tag.tag_id')
->where('properties.id','=',$property_id)
->get(['tags.tag_name','tags.id']);
you can try
$property_obj = Property::find($property_id);
$property_tags = $property_obj->tags->all();
or using eager loading
$property_with_tags = Property::with('tags')->where('id','=',$property_id)->get();
I have 4 tables that I'm trying to work with in Laravel and I can't figure out how to use eloquent to execute a particular query. I want to update all orders that belong to a user (through product_id) and that have null payout_id.
This raw sql statement works but I'm not sure how to use eloquent for this..perhaps sync?
UPDATE order_items i JOIN products p on (i.product_id = p.id) SET i.payout_id = null where p.user_id = 3
User Model
Product Model
FK: user_id
Order Model
FK: product_id
FK: payout_id
Payout Model
I would really appreciate any help!
First define a function orders in User Model
public function orders()
{
return $this->hasManyThrough('Orders', 'Product','user_id','product_id');
}
User::where('id','=',$userid)->with(array('orders'=>function($query){
$query->where('payout_id','=',0)->update(array('payout_id'=>$updatevalue));
}))->first();
You need to create a model for your tables i and p, see http://laravel.com/docs/eloquent for full information on model creation.
In the model for i you would then create a relationship to p:
public function p()
{
return $this->('p','id','product_id');
}
You can then run your query as follows:
$results = i::with('p')
->where('user_id', '=', 3)
->update(array('payout_id' => null));