I am creating a foreach loop with button attach (name)' for each model which is not connected to the base model with abelongsToMany` relation.
I have an array with IDs for a certain model
$attached_stages = $object->stages()->getRelatedIds()->toArray(); // output: 1, 2
Then I have all model instances for the same model,
$all_stages = Stage::orderBy('id', 'asc')->pluck('id')->all(); // output: 1,2,3,4 ... 6
$missing_stages = array_diff($all_stages, $attached_stages); // output: 3,4,5,6
My question: how to get a collection out of the $missing_stages array
The array is created as expected
My question (alternative solution)
What I am actually trying to get here is a collection of models which are not attached to the main $object with the stages() relation.
The relation is defined as follows:
public function stages()
{
return $this->belongsToMany('App\Models\Stage', 'lead_stage', 'lead_id', 'stage_id')->withPivot('id','status')->withTimestamps();
}
and I am unable to get my desired collection with this code:
$all_stages = Stage::get(); // output: collction 1,2,.... 6
$attached_stages = $object->stages(); // output: 1, 2
$missing_stages = $all_stages->diff($attached_stages); // expected output: 3,4,5,6
Note: I attempted to remove the pivot part in relation definition, but it didn't help, the diff method is not working for me. Nothing is cut from the collection.
Any help appreciated. Thx.
You can use whereNotIn() for your problem as:
$attached_stages = $object->stages()->getRelatedIds()->toArray();
$missing_stages = Stage::whereNotIn('id', $attached_stages)->get();
Related
So essentially I have two tables. Table 1 has a list of all attendants to a certain event. Table 2 has a list of all members of an organization that attended said event. I'm trying to copy a list of all non-members that attended the event. So the logic in my head is trying to loop through Table 2 and see if the value also exists in Table 1. If it does not, I'm trying to copy it into a list.
var attendants = currentS.getRange("M2:M").getValues(); //this is the list of all members that attended an event
for (var x = 2; x <= checkLast; x++) {
newcheck = currentS.getRange(x,5).getValue(); //this is getting the name of the attendants
if (attendants.indexOf(newcheck) == -1) {
var columnM = currentS.getRange("M1:M").getValues(); //trying to see if name of attendants is in the list of all members that attended the event.
var columnMlast = columnM.filter(String).length;
var final = currentS.getRange(columnMlast+1,13);
final.setValue(currentS.getRange(x,5).getValue()); //if it attendant is not in the list of members that attended, copies the name into a new list.
Whenever I run the code, I end up just getting the whole list of attendants without anything being filtered out. I hope I'm clear, and thanks in advance!!
Explanation:
You can use the filter method to find the items of attendants that are not included in the list of members and that will result in the list of new_members that will be appended at the bottom of members.
Using this solution you don't need for loops and most importantly you don't need to use setValue and getValue in a loop which is computationally expensive.
Solution:
I can't use your code because you have variables that aren't defined in the code snippet you provided.
I will show you an example (sheet and code) that you can use to adjust your current solution.
Example Script:
function myFunction() {
const ss = SpreadsheetApp.getActive();
const currentS = ss.getSheetByName("Sheet1");
const members = currentS.getRange("M2:M").getValues().flat().filter(r=>r!='');
const attendants = currentS.getRange("N2:N").getValues().flat().filter(r=>r!='');
const new_members = attendants.filter(a=>!members.includes(a)).map(nm=>[nm]);
console.log(new_members) // output: [ [ 'guest1' ], [ 'guest2' ], [ 'guest3' ], [ 'guest4' ] ]
currentS.getRange(members.length+2,13,new_members.length,1).setValues(new_members);
}
Example sheet (Input-Output):
This is my first post. I am in a trouble in my laravel project
Here is my data table.
I have student Id like 1,2,3. every students have multiple results followed by courses.
I need to arrange them like that
I tried groupby and got this result
Is there any possible way to arrange them according to students.
Thank You
code: controller:
public function notification()
{
$auth_id = Auth::user()->id;
$teacher = Teacher::where('user_id', $auth_id)->first();
$teacher_id = ($teacher->id);
$batch = Batch::where('teacher_id', $teacher_id)->first();
$courses = AssignCourses::with('course')
->where('semester_id', $batch->semester_id)
->get();
$current_semester_results = Result::with(['student', 'course'])
->where('semester_id', $batch->semester_id)
->get()
->groupBy('student.id');
$batch_students = Student::with('result')
->where('semester_id', $batch->semester_id)
->get();
return view('users.teacher.my_batch.notification', compact(['current_semester_results', 'courses', 'batch_students']));
}
Just use the $batch_students and apply any aggregations on your PHP code, it is easier to do it.
$batch_students = Student::with('result')
->where('semester_id', $batch->semester_id)
->get();
$batch_students_grouped = $batch_students->groupBy('result.student_id');
Note: I could not test since I don't have the tables, so you might need to change the student_id nest/access index in the last line of code.
you can print out your $batch_students_grouped->all() and see how you should iterate your data and show it in frontend.
Good day. Am trying to query my database to get the child of a child of a child. Every user has 2 children. Am using query builder. The requirements is not to use eloquent and eloquent relationships. But am struggling with it.
$firstchild= DB::table('users') - >where('parent_id', Auth::user() ->id) -> get() ;
$secondchild1 = DB::table('users') - >where('parent_id', $firstchild[0]->parent_id) -> get() ;
$secondchild2 = DB::table('users') - >where('parent_id', $firstchild[1]parent_id) -> get() ;
return view('home' ['firstchild' => $firstchild, 'secondchild1 ' => $secondchild1, 'secondchild2 ' => $secondchild2 , ])
It returns undefined offset 0 if the user child has no child. How do i do it if i want to get without any errors.
If I want to get the children of those children the query results gave, how will I do so?
Try this:
$firstchild = DB::table('users')->where('parent_id', Auth::user()->id)->get();
if ($firstchild->count() == 2) { //**Contains exactly 2 arrays inside the 'firstchild' collection.
$secondchild1 = DB::table('users')->where('parent_id', $firstchild[0]->parent_id)->get();
$secondchild2 = DB::table('users')->where('parent_id', $firstchild[1]->parent_id)->get();
}
return view('home', compact('firstchild', 'secondchild1', 'secondchild2'));
Hope it's helpful.
I'm working on a SRS-based Flashcard program in swift. My problem (other than being new at programming, haha) is... once I alter the values of due date, score, etc; how do I add them back to the wordBank array keeping the new property values?
I started out creating a class for other flashcards to inherit properties like word, translation, sentence 1 & 2, audio URL, score (1-100 for scheduling purposes), etc; etc;
class Flashcard {
var id: Int = 0
var score: Int = 0
var word: String = ""
var sentence1: String = ""
// etc; etc;
From here, I created a new file and class called words, inheriting the Flashcard properties.
class Words: Flashcard {
// Example word 1
let you = Flashcard()
you.id = 0
you.score = 2
you.word = "khun"
you.sentence1 = "khun blah blah"
// Example word 2
let me = Flashcard()
you.id = 1
you.score = 1
you.word = "pohm"
you.translation = "Me or I"
// Create an array of all the words that will be in the program
var wordBank: [Flashcard] = [you, me, him, her, them, it] // etc;
Now, from here I can sort
// Sort array by lowest
wordBank.sort({ $1.score > $0.score })
// Create a new array for testing Session
var SessionArray: [Flashcard] = []
// Add the lowest scores to the SessionArray for testing
SessionArray += WordArray[0...6]
For the sake of remembering, My problem is once I alter the values of due date, score, etc; how do I add them back to the wordBank array keeping the new property values? I won't bother asking about how to persist this data right now, lol. I'm still reading about core data.
Thanks for any help you can give me!
I have a product controller and when I'm saving a new product I want to save some records to another related controller to make a record of what categories the product is associated with.
My code I'm using is:
$this->Product->create();
if ($this->Product->save($this->request->data)) {
$newProductId = $this->Product->getInsertID();
//associate products with categories
foreach($categoriesToSave as $key=>$value) {
$saveArray['CategoriesProduct'] = array('category_id'=>$value, 'product_id'=>$newProductId);
$this->Product->CategoriesProduct->create();
$this->Product->CategoriesProduct->save($saveArray);
$this->Product->CategoriesProduct->clear();
}
}
For some reason though, even if $categoriesToSave has 10 items in it, only the very last one is being saved. So it's obviuosly creating only the one new CategoriesProduct item and saving each record over the top of the last instead of create()-ing a new one.
Can anyone explain what I'm doing wrong and how I can make this work?
The way I would do it would be like this:
//Add a counter
$c = 0
foreach($categoriesToSave as $key=>$value) {
$saveArray[$c]['CategoriesProduct']['category_id'] = $value;
$saveArray[$c]['CategoriesProduct']['product_id'] = $newProductId;
$c++;
}
$this->Product->CategoriesProduct->saveMany($saveArray);
I don't think that is the only way to do it but that should work just fine.
Good luck!