I have two columns member id and author id
Member A gives a list of author ids in a array format. I need to run a check against my database to see if these author ids are already there in my database, if they are present take the member ids of these authors and link them to the member id of A.
What is the efficient method to do this? Is it advisable to store the author ids to a temporary table and run the check and fetch it. The number of author ids in the array runs to few thousands.
Can you share some sample codes please? I am currently using PHP and MySql.
Update - I get an array of JSON objects with author id and name as follows:
{
"name": "Harold Robinson",
"id": "912065"
},
{
"name": "Gilbert Patten",
"id": "1212140"
},
{
"name": "Leo Tolstoy",
"id": "6012954"
}
I already have a table called Authors against which these data needs to be compared and if the ids match the user id assigned to the author has to be linked to User A.
Table Authors
User id: 109876
id: 912065
FYI, you won't get a useful answer if your question is not clear and with enough detail. This is a though one because the question is not very clear but I will attempt to the best of my understanding of the question. We can then tweak the answer as you clarify the question further.
//Not sure how you are collecting the ids into an array so I will just create one here for show.
$member_authors = array (1, 2, 3);
foreach ($member_authors as $authorID) {
$query = "SELECT author_id FROM authors WHERE author_id ='" . $authorID . "'";
$result = mysql_query($query);
if (mysql_affected_rows() > 0) { //If a value was returned then the author does exist in the database.
//Do whatever you want with the authorID.
}
}
I hope this helps.
Related
I have different communities in my database, such as: community_newsfeed, community_marketplace, community_games_requested, community_games_offered, events and custom_posts.
Each of those communities stores a post_id, as well as the user_id.
Then I have a community_users table that stores user_id and community_id.
I want to create a mechanism which I, as the authenticated user, can view all the posts of a user, as long as that user and I belong to the same community.
And on that regard, I must view only the posts for the communities which we both belong to.
So I do the following:
Get all the community id's of the communities which I(auth user) belong to:
$community_user_member = DB::table('community_users')->whereUserId($user->id)->pluck('community_id')->toArray();
Then I do the same for the user which I want to see the posts:
$requested_user = DB::table('community_users')->whereUserId($user_id)->pluck('community_id')->toArray();
Fine. Now I use array interect to give me all the community_id that we share only:
$members = array_intersect($community_user_member, $requested_user);
Now, this is where I get stuck.
How can I get the communities which the id match the values I get in the $members value(not the key) and the user id matches $user_id( this is passed in the url )?
if(!empty($members)){
$newsfeed = CommunityNewsfeed::whereIn('newsfeed_community_id', $members)->whereUserId($user_id)->get();
}
I am sure that this user has 4 posts from community_newsfeed table, but I only see two posts, and also I dont see the correct posts.
Live example:
User A belongs to community_newsfeed.
User B belongs to community_newsfeed and community_marketplace.
User A must see the community_newsfeed data where user_id is the id of User B.
Updated
Another option I tried was to use the in array function:
$common = [];
foreach ($community_user_member as $key => $member) {
if (in_array($member, $requested_user)) {
$common[] = $member;
}
}
print_r($common);
The end result should be something like this:
$common = [ '4','5','10','20' ];
Because then I would be able to loop through $common array and do whatever I want.
But I get the following error when I refresh the page:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
I'm quite new to Laravel and I'm trying to figure out how to properly work with Eloquent so far so good, but I'm stuck in something I want to do:
I have 3 tables in a database well 4 if you count the migrations one: food, food_group and portions which food_group and portion have the same structure which is and id as primary key and a name columns
the food ones have
| id(primary) | name | food_group_id (foreign key) | portion_id (foreign key |
all good because I have a nice formatted JSON with this in my route
Route::get('/read', function() {
$categories = App\FoodGroup::with('Foods')->get();
return Response::json(array('data' => $categories));
});
data: [
{
id: 1,
name: "Frutas",
foods: [
{
id: 18,
name: "Acelga",
cant_portion: 2
},
{
id: 19,
name: "Espinaca",
cant_portion: 2
},
]
}
]
and if I change the App\FoodGroup with App\Portion it gives me the same array but now ordered as the Foreign Key Portion
what I need is to first order with FoodGRoup and inside each item of the FFo_group one, now ordered by the second Foreign key which is Portion so I can have something like this
data: [
{
id: 1,
name: "Frutas",
portions:[
id: 18,
name: "Gr",
foods: [
{
id: 18,
name: "Acelga",
cant_portion: 2
},
{
id: 19,
name: "Espinaca",
cant_portion: 2
},
]
]
}
]
Your expected JSON shows foods as a child of portions. In order to do this, you need to setup this relationship.
On your Portion model, you need to setup the following relationship:
public function foods() {
return $this->hasMany(Food::class);
}
With this relationship setup, you can now get your data like this:
$categories = App\FoodGroup::with('portions.foods')->get();
This will load your food groups, then it will load the portions into the food groups, and then it will load the foods into the portions.
Edit
I may have slightly misread your question. I assumed you had a portions relationship defined on \App\FoodGroup. If not, you can add this like so:
FoodGroup:
public function portions() {
// the second parameter is the name of the pivot table.
// in this case, your foods table connects your portions and food groups.
return $this->belongsToMany(Portion::class, 'foods')->distinct();
}
Edit 2
This solution is a little hacky because it is treating the foods table as a pivot table, though it wasn't specifically designed for that. Because of this, there are multiple entries in the foods table that contain the same key pair values, and this is why you're getting duplicate related models.
If you throw a distinct() onto the relationship, this should take care of the issue, as it will eliminate the duplicates created from the inner join. The code above has been modified.
Based on the picture(ie your tables) you sent food_group does not have direct relationship with the portions so you can't chain food_group with portion like this
App\FoodGroup::with('portion.foods')
it should rather be (that is why you getting BadMethodCallException in Builder::portions())
App\FoodGroup::with('foods.portion')
because foodgroup has many foods and foods has many portion. so you can try something like this
App\FoodGroup::with(['foods.portion'=>function($q){
$q->orderBy('id')
}])->get();
I have made a custom dropdown field in leads module. Its a dynamically fetching users from users table from the leads module as key => value pair.
The field works fine but when in the edit mode (create a new lead)...the value is not getting stored and instead the key is getting stored not value..
I mean like instead of 'James Bond' the id is getting stored ..which is like '7896877'
Now the funny thing is that in the detail view in sugarcrm (leads module) the name is displayed properly as i wanted it to work. ONly in the list view it displays the ID and also in the database its getting stored as KEY i.e the hash ID.
This is the function:
function getUSERS($bean) {
$resultArray = Array();
$query = "select id,(first_name + ' ' + last_name) AS Name from dbo.users ORDER BY first_name ASC";
$resultArray [''] = '';
$result = $bean->db->query($query);
while ($row = $bean->db->fetchByAssoc($result)) {
$resultArray[$row['id']] = $row['Name'];
}
return $resultArray;
}
Dropdowns in Sugar work as key/value pairing, the key is what is stored in the database and Sugar does the appropriate lookup to display the value. Except the list view seems to work differently for dynamic dropdowns.
Instead of building your array as $resultArray[$row['id'] ]= $row['Name'] you could use the username -$resultArray[$row['username'] ]= $row['Name']as usernames have to be unique but will be more meaningful to your users in the list view.
However, is there any reason you're not using a relate field to the Users module? That should solve all your problems without any coding.
Current situation
I have two tables in my database, one for posts, and one for ratings. These are linked with a relation in the MySQL so that one post may have 0, 1 or multiple ratings, but one rating can only be applied to one post.
When I fetch a list of posts, I also want to get ratings, but without having to make a separate call to the database for each post in the foreach loop.
To do this I have attempted to use an SQL query to fetch all posts with a LEFT JOIN on ratings so that it will return a result like this:
statusId|statusBody|rating
-----------------------------
1, post1, 0
1, post1, 1
2, post2, 0
3, post3, 1
3, post3, 1
The SQL works fine, and I get the data I ask for.
Ideally what I am trying to achieve now is to turn this table into a collection of objects, with each object storing the post information as well as a value depending on it's total ratings.
After using PDO to return the data result, this is the code I am using to map the data:
Code Logic
The logic of my code goes like this:
Get all statuses joined with ratings table
Create empty output array
Loop through PDO result
{
Create loop specific temp array
Push first row of result into temp array
Remove row from PDO result
Loop through PDO result for objects with matching statusId
{
If row matches statusId, add to temp buffer and remove from PDO result
}
Take first row of buffer and create status object
Loop through objects in temp array to calculate ratings and add onto above status object
Clear temp buffer
Add status object to output array
}
return output array
Actual Code
try
{
$result = $pdo->query($sql);
//if($result == false) return false;
$statuses = $result->fetchAll(PDO::FETCH_CLASS, 'status');
}
catch (PDOException $e)
{
return FALSE;
}
if (!$result) {
return FALSE;
}
//create empty output array to be filled up
$status_output = array();
//loop through all status
foreach($statuses as $s1key => $s1value)
{
//initialise temporary array;
$status_temp_buffer = array();
//create temp array for storing status with same ID in and add first row
array_push($status_temp_buffer, $s1value);
//remove from primary array
unset($statuses[$s1key]);
//loop through array for matching entries
foreach($statuses as $s2key => $s2value)
{
//if statusId matches original, add to array;
if($s2value->statusId == $s1value->statusId)
{
//add status to temp array
array_push($status_temp_buffer, $s2value);
//remove from primary array
unset($statuses[$s2key]);
}
//stop foreach if statusId can no longer be found
break;
}
//create new status object from data;
$statObj = $status_temp_buffer[0];
//loop through temp array to get all ratings
foreach($status_temp_buffer as $sr)
{
//check if status has a rating
if($sr->rating != NULL)
{
//if rating is positive...
if($sr->rating == 1)
{
//add one point to positive ratings
$statObj->totalPositiveRatings++;
}
//regardless add one point to total ratings
$statObj->totalAllRatings++;
}
}
//clear temporary array
$status_temp_buffer = NULL;
//add object to output array
array_push($status_output, $statObj);
}
Problem
The problem I am coming up against with this code is that although the ratings are fine, and it correctly calculates the ratings total for each post, it still shows duplicates where a post has more than one rating.
Any help with this would be greatly appreciated,
Thanks
As i understood it, the goal is to get the total rating of each Post entry. Instead of manually looping over each and every rating, there are two other path you could take:
compute the total in the query:
SELECT SUM(rating) AS total , .. FROM Posts LEFT JOIN .... GROUP BY statusID
You will receive a list of Post entries, each already with total rating calculated. This is a very good solution if you have a lot of writes to to the Ratings table, and much less reads.
the other way is to break the table normalization, but to increase read performance. What you would have to do is to add another column in the Posts table: total_rating. And have an TRIGGER on INSERT in the Ratings table, which changes the Posts.total_rating accordingly.
This way has a benefit of simplifying the request of Posts. At the same time Ratings table can now be use to ensure that total_rating has been calculated correctly, or to recalculate the value, if there are some large changes in the ratings: like banning of user, which results in removing all ratings made by this user.
I have a collection named 'question'. Its structure looks like this:
{
_id:
user_id:
answers:
[
{
answer_id:
answer_content:
}
,
{
...
}
,
...
]
}
Now I know the document's _id and answer_id of one answer,now I want to set the answer to
be a best_answer(add a field to the element) for example:
{
answer_id:
answer_content:
is_best:true
}
How can I do this?
You'll need to update the question document in the questions collection, one way is to $push the user info onto a answeredBy array field of some sort. Alternately you could create a separate answers collection and push answer documents containing the question id, uid, name, and answer.
$find_array = array('answers._id'=>$answer_id);
$this>collection>update($find_array,array('$set'=>array('answers.$.is_best' => true)));