Using relational table field in grocery crud list view - grocery-crud

I have a tables user, user_dealer and dealer. user.id and dealer.id is stored in user_dealer as user_id and dealer_id (many 2 many).
Using this code in Grocery Crud:
$crud->set_relation_n_n('Dealer', config_item('db_prefix') . 'user_dealer', config_item('db_prefix') . 'dealer', 'user_id', 'dealer_id', 'dealer');
$crud->columns('firstname', 'lastname', 'username', 'email', 'dealer_code', 'active',' lockdate');
The dealer_code field is in the dealer table. Since it is a many 2 many relationship, how do I display the dealer_code in the list view? It can be any one of the dealer codes if there are multiple ones.

In your case you will do something like this:
$crud->set_relation_n_n('dealer', config_item('db_prefix') . 'user_dealer', config_item('db_prefix') . 'dealer', 'user_id', 'dealer_id', 'dealer');
$crud->columns('firstname', 'lastname', 'username', 'email', 'dealer', 'active',' lockdate');
So in your case we just renamed the "Dealer" to 'dealer' and we did call it at the columns as a 'dealer' and now you can actually call the dealer names and they will be separated by comma.
If still this is not what are you looking for and you need to show the dealer_id separated with commas and not the names then you will need to use the set_model at: http://www.grocerycrud.com/documentation/options_functions/set_model . As this is a known issue and set_model was firstly created for relation_n_n to do more complicated stuff, there is also an example at the page that you can see and help you.

Related

Odoo select all records where user is follower

Can somebody give me example (or hint) how to select all records where user is follower?
I cant find any information about handling followers. What the condition should be?
find_record = self.env['my_class'].search([( **user is floower** )])
Followers are related to partners, you can select records where current user related partner is in followers:
self.env['sale.order'].search([('message_follower_ids.partner_id', '=', self.env.user.partner_id.id)])
try the following
first element of the tuple : the partner id related to the user
2nd element of the tuple : the logical operator 'in'
3rd element of the tuple : the id of partners following the record
self.env['helpdesk.ticket'].search([(self.env.user.partner_id.id, 'in', 'message_follower_ids.partner_id')])

How do I do a joined lookup with search.lookupFields()?

I'm trying to get some information about an item, including the item's subsidiary's logo, which naturally requires joining the item to the subsidiary.
The documentation for search.lookupFields says:
You can use joined-field lookups with this method, with the following syntax:
join_id.field_name
So, I duly request the fields I want, including a join on subsidiary:
require(['N/search'], function(search) {
var item = search.lookupFields({
type: search.Type.ITEM,
id: 2086,
columns: ['itemid', 'displayname', 'subsidiary.logo'],
});
log.debug(item);
});
itemid and displayname are fine, but when I try to join another record I get this error:
{
"type":"error.SuiteScriptError",
"name":"SSS_INVALID_SRCH_COLUMN_JOIN",
"message":"An nlobjSearchColumn contains an invalid column join ID, or is not in proper syntax: logo.",
"stack":["doLookupFields(N/search/searchUtil.js)","<anonymous>(adhoc$-1$debugger.user:2)","<anonymous>(adhoc$-1$debugger.user:1)"],
"cause":{
"type":"internal error",
"code":"SSS_INVALID_SRCH_COLUMN_JOIN",
"details":"An nlobjSearchColumn contains an invalid column join ID, or is not in proper syntax: logo.",
"userEvent":null,
"stackTrace":["doLookupFields(N/search/searchUtil.js)","<anonymous>(adhoc$-1$debugger.user:2)","<anonymous>(adhoc$-1$debugger.user:1)"],
"notifyOff":false
},
"id":"",
"notifyOff":false,
"userFacing":false
}
This seems to happen no matter which record and field I try to join. What am I missing?
Although you can return results from multi-select fields, you cannot join to fields on records referenced by multi-select fields (which the subsidiary field on the item record is). Also, you cannot search the logo field on the subsidiary record (not listed in Search Columns under Subsidiary in the NetSuite Records Browser).
This means you have to load the Subsidiary record to get the logo field. In other words:
require(['N/record', 'N/search'], function(record, search) {
var item = search.lookupFields({
type: search.Type.ITEM,
id: 2086,
columns: ['itemid', 'displayname', 'subsidiary'],
});
var subID = item.subsidiary[0].value; //internal id of *first* subsidiary
var subRec = record.load({
type: record.Type.SUBSIDIARY,
id: subID
});
var logo = subRec.getText('logo'); //gets the file name - use getValue to get its ID instead
});
Note that if multiple subsidiaries are set on the item, this only gets the values for the first one. You could iterate through the item.subsidiary result to handle values for multiple subsidiaries if required.
I believe you can't access to the subsidiary record from a lookupfield, you should do a proper search.
https://system.netsuite.com/help/helpcenter/en_US/srbrowser/Browser2018_2/script/record/item.html
You can only join to tables allowed in the Item search object. Try looking for "Subsidiary..." in the Search Results tab within the UI. It's not there. Use the Schema Browser to determine what fields and joins are available.
You cannot think of a NetSuite search as you would any regular SQL search. You have to be cognizant of which fields and which joins can be utilized via the search object.
As people have mentioned, the subsidiary is not a join field available from the item record, one way to achieve what you are trying to do is:
Make a lookup to get the internal id of the subsidiary belonging to the desired item.
Then make a lookup to get the internal id of the logo image (file cabinet image) belonging to the previous subsidiary.
Make another lookup/load the image file to get the URL of the image/logo
You can try to combine the above steps in a single saved search but I think you might need to load the image file to get the URL.
This won't answer your question, but this may help out in the future. The records browser shows everything that you can search and join on, columns and filters, and field IDs. Very useful when building out searches.
NetSuite Records Browser - 2018.2

Suitescript 2 list.addRows from search results that have a join

I have a Suitescript search that is returning the following columns.
{"columns":[{"name":"trandate","label":"Date","type":"date","sortdir":"ASC"},{"name":"refnumber","label":"Reference Number","type":"integer","sortdir":"NONE"},{"name":"closedate","label":"Date Closed","type":"date","sortdir":"NONE"},{"name":"custbody_eft_bill_payment","join":"payingTransaction","label":"EFT Bill Payment","type":"checkbox","sortdir":"NONE"},{"name":"tranid","join":"payingTransaction","label":"Check Number","type":"text","sortdir":"NONE"},{"name":"amount","label":"Amount","type":"currency","sortdir":"NONE"}]}
And I am using the list.addRows() method to display the results in a suitelet list where I have defined the columns using the list.addColumns() method but I have not been able to successfully get the columns that are created from a join. I also can find no documentation on how to include them. I have tried the following
list.addColumn({
id: 'payingTransaction.tranid',
label: 'Payment#',
type: ui.FieldType.TEXT,
})
list.addColumn({
id: 'tranid',
label: 'Payment#',
type: ui.FieldType.TEXT,
})
Any help would be appreciated!
Not sure if this will help, but when running through your results you can use one of two methods to get the resulting data:
Use the join in the getValue() call
results.getValue({name:"tranid",join:"payingTransaction"});
Grab the data by Columns
var columns=result.columns;
var tranid=result.getValue(columns[0]);
The first option will need to be told whether it is a join, group, etc...
The second option will just grab the resulting column, no matter whether it is a join, group, or anything else.

loopback relational database hasManyThrough pivot table

I seem to be stuck on a classic ORM issue and don't know really how to handle it, so at this point any help is welcome.
Is there a way to get the pivot table on a hasManyThrough query? Better yet, apply some filter or sort to it. A typical example
Table products
id,title
Table categories
id,title
table products_categories
productsId, categoriesId, orderBy, main
So, in the above scenario, say you want to get all categories of product X that are (main = true) or you want to sort the the product categories by orderBy.
What happens now is a first SELECT on products to get the product data, a second SELECT on products_categories to get the categoriesId and a final SELECT on categories to get the actual categories. Ideally, filters and sort should be applied to the 2nd SELECT like
SELECT `id`,`productsId`,`categoriesId`,`orderBy`,`main` FROM `products_categories` WHERE `productsId` IN (180) WHERE main = 1 ORDER BY `orderBy` DESC
Another typical example would be wanting to order the product images based on the order the user wants them to
so you would have a products_images table
id,image,productsID,orderBy
and you would want to
SELECT from products_images WHERE productsId In (180) ORDER BY orderBy ASC
Is that even possible?
EDIT : Here is the relationship needed for an intermediate table to get what I need based on my schema.
Products.hasMany(Images,
{
as: "Images",
"foreignKey": "productsId",
"through": ProductsImagesItems,
scope: function (inst, filter) {
return {active: 1};
}
});
Thing is the scope function is giving me access to the final result and not to the intermediate table.
I am not sure to fully understand your problem(s), but for sure you need to move away from the table concept and express your problem in terms of Models and Relations.
The way I see it, you have two models Product(properties: title) and Category (properties: main).
Then, you can have relations between the two, potentially
Product belongsTo Category
Category hasMany Product
This means a product will belong to a single category, while a category may contain many products. There are other relations available
Then, using the generated REST API, you can filter GET requests to get items in function of their properties (like main in your case), or use custom GET requests (automatically generated when you add relations) to get for instance all products belonging to a specific category.
Does this helps ?
Based on what you have here I'd probably recommend using the scope option when defining the relationship. The LoopBack docs show a very similar example of the "product - category" scenario:
Product.hasMany(Category, {
as: 'categories',
scope: function(instance, filter) {
return { type: instance.type };
}
});
In the example above, instance is a category that is being matched, and each product would have a new categories property that would contain the matching Category entities for that Product. Note that this does not follow your exact data scheme, so you may need to play around with it. Also, I think your API query would have to specify that you want the categories related data loaded (those are not included by default):
/api/Products/13?filter{"include":["categories"]}
I suggest you define a custom / remote method in Product.js that does the work for you.
Product.getCategories(_productId){
// if you are taking product title as param instead of _productId,
// you will first need to find product ID
// then execute a find query on products_categories with
// 1. where filter to get only main categoris and productId = _productId
// 2. include filter to include product and category objects
// 3. orderBy filter to sort items based on orderBy column
// now you will get an array of products_categories.
// Each item / object in the array will have nested objects of Product and Category.
}

How to reference one foreign key column with multiple primary key column

I am creating BOOK_Issue table which will contain id of person to whom the book is issued.
i have a column name user_id witch will contain ids from tbl_student as well as tbl_faculty. so how to set user_id field of book_issue table with reference to two primary key columns.
Your database schema is not correct.
If you expect unique IDs then they should be in one table.
You can create a table with all the users, and have a column to set their type (student, faculty). Then create 2 different tables for each type that has the proper information for each user based on their type.
Create a "person" superclass that can be either of type "student" or type "faculty". Reference this from the BOOK_Issue table instead.
Basically to create this relationship, you'll need one unique ID that spans both "student" and "faculty". Put this in a table (tbl_person?) and have each row in tbl_student and tbl_faculty reference this new table. It's probably also best to then pull out the fields present in both tbl_student and tbl_faculty and put them in this new supertable instead.
You can solve the problem by either having an extra column in BOOK_Issue table, next to user_id, which indicates if this is a Student ID or a Faculty ID.
Alternatively, the IDs themselves may readily include some pattern which indicate their nature (for example no all faculty Ids may start with say "UC", and none of the student Id are so).
The two solutions above then allow using queries similar to the following
SELECT B.*,
CASE B.BorrowerType -- could be LEFT(user_id, 2) etc...
WHEN 'S' THEN S.Name
WHEN 'F' Then F.Name
END As Name,
CASE B.BorrowerType
WHEN 'S' THEN S.PhoneNumber
WHEN 'F' Then F.Phone -- Note that these constructs allow
-- mapping distinct columns names etc.
END As PhoneNr
FROM BOOK_Issue B
LEFT JOIN tbl_student S ON B.BorrowerType = 'S' AND B.user_id = S.id
LEFT JOIN tbl_faculty F ON B.BorrowerType = 'F' AND B.user_id = F.id
WHERE B.DueDate < '11/23/2009' -- or some other condition
This can get a bit heavy when we need to get multiple columns from the student/faculty tables. A possible alternative is a UNION, but this would then cause the repeating of the search clause.
Finally, the best solution but not avaible on all DBMS is a sub-query driven by an "IF B.BorrowerType = 'S' " condition.
This should be your table design:
FacultyTable (FacultyID, FacultyName)
StudentsTable (StudentID, StudentName, FacultlyID, ...)
BookTable (BookID, BookName, ...)
UsersTable(UserID, UserName, UserPassword, StudentID, LastLogin, ...)
Now this is the main thing:
BookIssedTable(BookIssedID, BookID, UserID)
//This table tells me that a book of "BookID was issued to a user of "UserID"
//this can be better for this is certainly a great improvement from the initial design.

Resources