How can I remove duplicates results when using belongsToMany - laravel

Having the following tables:
----------- ----------------- ---------------
| PROJECT | | ACCESSES | | ENVIRONMENT |
----------- ----------------- ---------------
| id | | id | | id |
| title | | project_id | | title |
----------- | environment_id| ---------------
| username |
| password |
-----------------
My goal is to get all the environments used by a project through the accesses table
In my Project model:
public function environments(){
return $this->belongsToMany('App\Models\Environment', "accesses");
}
My problem is that if I have multiple rows with the same project_id and environment_id values in the accesses table, it will fetch multiple time the same environment.
How may I force it to retrieve each environment only once?

This is an old question, but the benefit of future travellers:
The distinct() method can help in this situation:
public function environments() {
return $this
->belongsToMany('App\Models\Environment', "accesses")
->distinct();
}
From the docs:
The distinct method allows you to force the query to return distinct results:
$users = DB::table('users')->distinct()->get();
As far as I can tell, this works at least as far back as Laravel 4.x, so it should be fine for all currently supported versions.

You can achieve this using sync method or toggle method it depends on your use case.
From the docs:
The many-to-many relationship also provides a toggle method which "toggles" the attachment status of the given IDs. If the given ID is currently attached, it will be detached. Likewise, if it is currently detached, it will be attached:
$project->environments()->toggle([1, 2, 3]);
You may also use the sync method to construct many-to-many associations. The sync method accepts an array of IDs to place on the intermediate table. Any IDs that are not in the given array will be removed from the intermediate table. So, after this operation is complete, only the IDs in the given array will exist in the intermediate table
$project->environments()->sync([1, 2, 3]);
For more information please have a look in the docs.
https://laravel.com/docs/5.6/eloquent-relationships#updating-many-to-many-relationships

Related

How to create an AppSync GraphQL prefixed / complex type `?id=ID` rather than just `ID!`

Given some knowledge about single table design in DynamoDB, I would like to have generic attribute names.
What I'm trying to create:
PK | SK | LSI1 | ...
---------------------------------------------------
PRODUCT | ?id=1234-1234-1234 | ?type=shoe | ...
---------------------------------------------------
Rather than the default:
id | type1 | type2 | ...
------------------------------------------------------
1234-1234-1234 | PRODUCT | shoe | ...
------------------------------------------------------
My question:
How can I specify the type for SK in the first example? I would like to specify that it's a String of format ?id= and ID!
You specify these things in the application code and keep the PK and SK as strings always.
They usually look like this
PK SK
Type#{productType} ProductId#{productId}
Then productType and productId should also we included as attributes so you can use the data and not extract it from the PK and SK.

Laravel's Eloquent. One/many to many of different models (types)

I've got a model that can be related to arbitrary number of items (other models). What is the best way to retrieve those as an array/collection of items of their types, e.g.
$basket = Basket::find(1);
dd($basket->items); // [Banana, Yoghurt, Bread, Bread, Ham, Cheese, Cheese]
Table: basket
| id | int |
| user_id | int |
Table: basket_items
| id | int |
| basket_id | int |
| item_id | int |
| item_type | string |
Models: Basket, Banana, Yoghurt, Bread, Ham, Cheese
Where I've got so far is: I can not use Eloquent's relations here since items method is referencing multiple models. The question is: can I (probably don't see how)?
As a plan-B I'd just implement that Basket::items method issuing a query and then fetching each and every model and hydrating them. I wonder if there a better way of dealing with that.

Relationship Model in Laravel?

This question is about the Laravel style of doing things:
Everything in Laravel can be done in an elegant way.
I currently have a many to many relationship between mongrels and breeds through a table named breed_mongrel but this table also has a certainty value describing how certain the dog is that he's indeed a mix of that specific breed.
mongrel_id | breed_id | certainty|
----------------------------------
| 1 | 4 | 50 |
| 1 | 2 | 25 |
| 2 | 5 | 75 |
this means that mongrel#1 is 50% sure she's of breed#4 and 25% sure she's also a mix with breed#2. However mongrel#2 is a whooping 75% certain he is breed#5.
My question is what is the elegant way to add records to this table?
I could use something like this:
DB::table('breed_mongrel')->insert(
array('mongrel_id' => 3, 'breed_id' => 5, 'certainty' => 37));
But in Laravel I would normally do things more eloquently like:
$relation = new Relation;
$relation->breed_id = 1;
$relation->save();
But because it is a relationship and I can't follow the normal model named in singular camel caseform and DB table named in plural lower (snail) case I'm not sure what is Laravelly way to add entries to this database table?
You can use attach. It also accepts a second parameter allowing extra values to be added to the pivot table.
$mongrel = Mongrel::find(1);
$breed = Breed::find(4);
$mongrel->breeds()->attach($breed, array('certainty' => '50'));

set values in form fields in edit mode when data comes from multipal tables

I am developing a custom module for a project. I created a custom form and that custom form's data saved in two tables. Now when form open in edit mode I am not able to get saved data from both tables. I have no idea how can I get resolve this issue, please help me.
Here are my two tables structures:
Table1-
-------------------------
id | page_id | title
1 | 3 | ABC
2 | 4 | PQRS
3 | 10 | XYZ
Table2-
--------------------------------
id | page_id | child | position
1 | 3 | 8 | left
2 | 3 | 7 | right
3 | 3 | 15 | right
4 | 4 | 14 | right
5 | 4 | 15 | left
6 | 10 | 15 | left
--------------------------------
Here i am attaching a screen-shot to more explain myself. I want to selected saved option values in 'left' & 'right' text-area in edit mode, values comes from table2.
Please suggest me. Thanks in advance.
Left and Right are here multiselect field types and these kind of fields receives values in comma separated string. so the example you presented will work in this way.
lets consider you have models Table1 and Table2 and you pass your Table Model from edit action in you controller you have written
$table1Id = $this->getRequest()->getParam('id');
$table1Model = Mage::getModel('page/table1')->load($table1Id);
if ($table1Model->getId()) {
Mage::register('page_data', $table1Model);
...
In your form file Block/Adminhtml/Edit/Tab/Form.php there is method $form->setData()
if ( Mage::getSingleton('adminhtml/session')->getPageData() )
{
$form->setValues(Mage::getSingleton('adminhtml/session')->getPageData());
Mage::getSingleton('adminhtml/session')->setPageData(null);
}
elseif ( Mage::registry('page_data') ) {
$values = Mage::registry('page_data')->getData();
$values['left'] = '8';//You can get this value from Table2 collection on basis of $values['page_id'] you got
$values['right'] = '7,15';////You can get this value from Table2 collection on basis of $values['page_id'] you got
$form->setValues($values);
}
I found the solutions of my query.
This extension is the best example click here
To get resolve this need to edit many files like model, resource and block files. That's why I mentioned this link to understand complete process.
most file that are need attention are :
app/code/community/[PackageName]/[ModuleName]/Model/Resource/Pagesummary.php
app/code/community/[PackageName]/[ModuleName]/Model/Pagesummary.php
app/code/community/[PackageName]/[ModuleName]/Block/Adminhtml/Cms/Page/Edit/Tab/Pagesummary.php
hope this helps others!

YUI DataTable nested columns with JSON object with unknown keys

I am pretty new to YUI and need some help.
I have a JSON response like this:
{
"Results":[
{
"alpha":57.935,
"beta:{
"delta":2.975,
"omega":1.431
},
"gamma":{
"theta":"0.339",
"lambda":"1.195"
}
},
{
"alpha":87,
"beta":{
"lambda":2.680,
"kappa":0.714
},
"gamma":{
"zeta":"0.288",
"epsilon":"0.289"
}
}
]
}
I would like to have a datatable with nested columns where:
1) alpha, beta and gamma are parent columns.
2) beta and gamma each have two columns formed of the JSON key-value pair (e.g., delta => 2.975).
3) The number of rows, i.e., total key-value pairs, is dynamic.
Basically, something like this:
----------------------------------------------
| alpha | beta | gamma |
----------------------------------------------
| 57.935 | delta | 2.975 | theta | 0.339 |
----------------------------------------------
| | omega | 1.431 | lambda | 1.195 |
----------------------------------------------
| 87.435 | lambda | 2.680 | zeta | 0.288 |
----------------------------------------------
| | kappa | 0.714 | epsilon | 0.289 |
----------------------------------------------
I have been able to generate non-nested, simple JSON responses.
My problems:
1) I have the object for each JSON child ({theta:0.339}, etc.). Both child columns will need data from this same object. How do I use it without modifying it? Should I use the same 'keyName' for both child columns in myColumnDefs?
2) How to create more than one rows where alpha td is empty?
Any help will be appreciated !
This is not an easy problem to solve. Barring your ability to format the JSON into individual rows before its sent to the client, you can hack together a solution using some column configurations, formatters, and a custom bodyView modelList attribute setter that flattens the data for display.
http://jsbin.com/3/efigim/1/edit?javascript,live
This would likely involve some breakage of table row -> data record associations since the bodyView's modelList contains its own Models for the rows rather than sharing a clientId. This may or may not get in your way, depending on whether you need additional features.
But since the DataTable's data ModelList preserves the objects for beta and gamma values--only the view's representation is customized--you might be fine.
YMMV, HTH

Resources