retrieving data from two tables based on a condition - mysql

I have two tables TABLE users and TABLE assign_project. I need to get those user id that are not in assign_project table based on the role_id.
The fields in users table:
- user_id
- username
- role_id
- company_id
The fields in the assign_project table:
- id
- project_id
- user_id
The code is
$company_id = 1;
//get the project details of the project $project_id
$projects = Project::where('project_id','=',$project_id)->get();
//get the company id of the project $project_id
$company_id = Project::where('project_id','=',$project_id)->value('company_id');
//get the users whom the $project_id is assigned
$users = DB::table('assign_project')
->where('project_id','=', $project_id)
->get();
// if $project_id is assigned to any user retrieve only those
//with role id = 2 and with the company id $company_id
//whom $project_id is not assigned
foreach ($users as $row) {
$designation = User::where('user_id','<>',$row->assigned_to)
->where('role_id','=',2)
->where('company_id','=',$company_id)
->get();
}
I am not getting the output.

Related

I have Product and Category Many to Many Relation. I need to fetch Product where category_id(in pivot table) = [1,2,3,4]

I have Product and Category Many to Many Relation. I need to fetch Product where category_id(in pivot table) = [1,2,3,4]
in my Category Model
public function all_product($categories_ids): BelongsToMany
{
return $this->belongsToMany(Product::class)->wherePivotIn('category_id', $categories_ids);
}
and in controller
$categories_ids = [1,2,3,4];
$category = Category::where('slug_id', $request->input('slug_id'))->first();
$product = $category->all_product($categories_ids)->get();
return $product;
here I get only associated product with that $category. but I need all product whose category_id are $categories_ids = [1,2,3,4].
please help me to solve this query. thank you

How to get today's all orders by restaurant in laravel?

I'm trying to get today's orders by a restaurant. Here is my table structure
restaurants
id - integer
name - string
categories
id - integer
restaurant_id- foreign
name - string
items
id - integer
category_id - foreign
name - string
orders
id - integer
amonut- double
order_items (pivot table)
id - integer
order_id - foreign
item_id - foreign
Here is my restaurant model
public function restaurant_categories() {
return $this->hasMany(Category::class, 'restaurant_id')->orderBy('created_at', 'DESC');
}
public function restaurant_items() {
return $this->hasManyThrough(Item::class, Category::class, 'restaurant_id', 'category_id')->with('category', 'item_assets')->orderBy('created_at', 'DESC');
}
Here is my Item model
public function orders(){
return $this->belongsToMany(Order::class,'order_items','item_id', 'order_id' )
->withPivot('quantity','price');
}
By this code, I get specific restaurant's all orders
$restaurant = Restaurant::with('restaurant_items')->find($id);
$orders = [];
foreach ($restaurant->restaurant_items as $item) {
$orders[] = $item->orders;
}
But now, How & where can I add where condition to get only today's order? and also if I want to get specific date's orders then what to do?L
For Laravel 5.6+ version, you can just have to add whereDate() condition
$restaurant = Restaurant::with('restaurant_items')
->whereDate('created_at', Carbon::today())->get();
Or you can also use whereRaw()
$restaurant = Restaurant::with('restaurant_items')
->whereRaw('Date(created_at) = CURDATE()')->get();

How to get Current Product Seller Id in magento

How to get Current Product Seller Id in magento.If I can get the Id I can show up their address country. Is there Anyone can help me with this?
I get the seller name by attribute
<?php echo $_product->getAttributeText('creator_id');?>
From Product ID you can get its seller name, below is code sample for it ( magento 1.9)
$ProductID = 1000; ///$_product->getProductId(); you can get it like this
$allSellers= Mage::getModel('marketplace/product')->getCollection()->addFieldToFilter('mageproductid',array('eq'=> $ProductID ));
$sellerID = 0;
foreach ($allSellers as $seller) {
$sellerID= $seller->getUserid(); // here you have seller ID
$sellerName = Mage::getModel('customer/customer')->load($sellerID)->getName(); // here you have seller name
}
This codes can be used if you are using Marketplace Extension.
Assuming the product ID is 10.
$prodID = 10;
$collection_prod = Mage::getModel('marketplace/product')->getCollection()->addFieldToFilter('mageproductid', array('eq'=>$prodID));
$sellerID = '';
foreach($collection_prod as $collection){
$sellerID = $collection->getUserid(); //get the seller ID
}
$sellerAddress_Collection = Mage::getModel('customer/address')->getCollection()->addFieldToFilter('parent_id', array('eq'=>$sellerID));
foreach($sellerAddress_Collection as $sellerAddress_Collections){
$addressID = $sellerAddress_Collections->getEntityId(); //get the address ID of the seller
$seller_collection_address = Mage::getModel('customer/address')->load($addressID); // load the address ID of the seller
$zipcode = $seller_collection_address->getPostcode(); //zipcode
$country_id = $seller_collection_address->getCountryId(); //country id
$city = $seller_collection_address->getCity(); // City
$street1 = $seller_collection_address->getStreet(1); //street 1
$street2 = $seller_collection_address->getStreet(2); //street 2
$tel = $seller_collection_address->getTelephone(); //Telephone
}

how can I connect these two tables in sql?

i need to take only the items from the table "__sobi2_item" that are in the same country of the user.And use this results for the rest of the function Showupdatelisting. This is my php script:
<?php
function showUpdatedListing()
{
//i found the user country field value...
global $database;
$user =& JFactory::getUser();
$userId = $user->get( 'id' );
$sql = "SELECT (id) FROM #__community_fields WHERE fieldcode= 'FIELD_COUNTRY'";
$database->setQuery( $sql );
$fieldID = $database->loadResult();
$sql = "SELECT (value) FROM #__community_fields_values WHERE field_id= {$fieldID} && user_id= {$userId}";
$database->setQuery( $sql );
$usercountry = $database->loadResult();
// From all the entries i take only ones that have country field like the user has...
$query = "SELECT `data_txt`, `itemid`, `fieldid` FROM `#__sobi2_fields_data` WHERE (`fieldid` = 6) AND ('data_txt' = {$usercountry})";
$database->setQuery($query);
$ResultsArray = $database->loadObjectList();
// We need something here like a Query to load only the entries from $ResultsArray... ??
//....instead of this...
$config =& sobi2Config::getInstance();
$database = $config->getDb();
$now = $config->getTimeAndDate();
$query = "SELECT itemid FROM #__sobi2_item WHERE (published = 1 AND publish_down > '{$now}' OR publish_down = '{$config->nullDate}') ORDER BY last_update DESC LIMIT 0, 30";
$database->setQuery($query);
$sids = $database->loadResultArray();
// ......... show update function goes on...
?>
can anyone help me to connect and adjust these query? thanks.
NB:with the last query (4) i need to filter items of the $ResultsArray taking only ones published and ordering them by last_update. i know it is wrong and now there is no connection with the query before. This is how i have tables in mysql:
_sobi2_fields_data:
itemid
fieldid
data_txt --->(is a description column for each field)
_sobi2_item:
itemid
published --->( 1 if true, 0 if false )
last_update --->(date of the last update for the item, also equal to the publication date if there are no changes)
thanks.
I don't know what you are trying to ask as well. Your last query (number 4) doesn't make sense to me, how is it linked to the above queries?
[EDIT] I've linked your 4th table above assuming itemid is the primary key for the items in sobi2_item table and that the value is linked to the sobi_fields_data table via itemid.
SELECT
cf.id,
sfd.data_txt,
sfd.itemid,
sfd.fieldid
FROM #__community_fields cf
INNER JOIN #__community_fields_values cfv ON cf.id=cfv.field_id
INNER JOIN #__sobi2_fields_data sfd ON cfv.value=sfd.data_txt
INNER JOIN #__sobi2_item si ON sfd.itemid=si.itemid
WHERE cf.fieldcode='FIELD_COUNTRY'
AND cfv.user_id=$userId
AND sfd.fieldid=6
AND si.published=1
AND (si.publish_down > '{$now}' OR si.publish_down = '{$config->nullDate}')
ORDER BY si.last_update DESC LIMIT 0, 30
Good luck!

How to combine sql select queries for this situation?

i'm writing a chat app with php/mysql
i have 3 tables: user, room and room_participant with these structures:
user: id, username
room: id, title
room_participant: room_id, user_id
Now i want to get list of all rooms along with list of all participants in each room.
Until now i just select all rooms from room table and iterate through all rooms and select users information out of each entry, which is very inefficient.
Is there any way to combine all these select into only 1 select query?
Not certain about this without testing, but give it a try:
SELECT
room.*,
user.*
FROM room
JOIN room_participant ON room_id = room_participant.id
JOIN user ON room_participant.user_id = user.id
ORDER BY room.id
To deduplicate rooms, use GROUP_CONCAT()
UPDATE GROUP_CONCAT() modified to return id|username
SELECT
room.id, room.name
GROUP_CONCAT(CONCAT(user.id,'|',user.username)) AS userlist
FROM room
JOIN room_participant ON room_id = room_participant.id
JOIN user ON room_participant.user_id = user.id
GROUP BY room.id, room.name
ORDER BY room.id
With the userlist generated by GROUP_CONCAT as id|name,id|name,id|name you can use PHP explode() to separate them.
// Split the list on the commas
$users = explode(",", $userlist);
$final_users = array();
// Then split each on the `|`
foreach ($users as $user) {
$split_user = explode("|", $user);
// Append each as a new associative array to $final_users
$final_users[] = array('id' => $split_user[0], 'username' => $split_user[1]);
}
// Now you have an array of users as id, username
var_dump($final_users);
You may wish to do two queries, and then match things up in whatever is using MySQL, e.g. PHP.
These two:
SELECT id, title
FROM room;
SELECT rp.room_id, rp.user_id, u.username
FROM room_participant AS rp
INNER JOIN user as u ON rp.user_id = u.id;
Or these two:
SELECT id, username
FROM user;
SELECT rp.room_id, rp.user_id, r.title
FROM room_participant AS rp
INNER JOIN room as r ON rp.user_id = r.id;
Which two queries make sense depends on what you're doing with the info really.
You could go a step further and select all three separately:
SELECT *
FROM room;
SELECT *
FROM user;
SELECT *
FROM room_participant;
Note: It's probably better to state the columns, rather than using '*', just in case in the future new columns are added to the table that you're not really interested in for these queries.
Obviously, you'd then have to match everything up in whatever is using MySQL, e.g. PHP. You could create a list of rooms and users from the selected info, and then match them up with something like:
// Use MySQL to populate $roomList from database, then do...
foreach ($roomList as $room)
{
$id = $room['id'];
$title = $room['title'];
$this->roomList[$id] = new Room($id, $title);
}
// Use MySQL to populate $userList from database, then do...
foreach ($userList as $user)
{
$id = $user['id'];
$username = $user['username'];
$this->userList[$id] = new User($id, $username);
}
// Use MySQL to populate $roomParticipantList from database, then do...
foreach ($roomParticipantList as $roomParticipant)
{
$room = $this->roomList[$roomParticipant['room_id']];
$user = $this->userList[$roomParticipant['user_id']];
// You could do one/both of these, depending on requirements.
$room->enterUser($user);
$user->joinRoom($room);
}