laravel join table if data exists - join

What is the best way to join table A with table B, if table B has data and if not just give me data from table A? because if I do it in this way, and there are no photos in table B I don't get data from that row from table A.
$data = Category::join('photos', 'categories.cover_id', '=', 'photos.id')
->get(['categories.id',
'categories.position',
'categories.visible',
'categories.created_at',
'categories.updated_at',
'categories.title',
'photos.filename']);
return $data;
my idea is just to make another request to get all data from table A where categories.cover_id is 0 (without join)
my tables are just
table A (categories)
-------------------------------
| id | title | cover_id | ... |
-------------------------------
| 1 | lorem | 1 | ... |
-------------------------------
| 2 | ipsum | 12 | ... |
-------------------------------
| 3 | dolor | 0 | ... |
-------------------------------
table B (Photos, there is no data for dolor, because i created dolor recently in table A)
---------------------------------
| id | title | filename | ... |
---------------------------------
| 1 | lorem | lorem.jpg | ... |
---------------------------------
| .. | ..... | ...jpg | ... |
---------------------------------
| 12 | ipsum | ipsum.jpg | ... |
---------------------------------

You should be fine by just using a leftJoin(). A normal ("inner join") will only return results from both tables. But a left join returns all results from the left table (in this case categories) and everything that exists from the other table.
$data = Category::leftJoin('photos', 'categories.cover_id', '=', 'photos.id')
->get(['categories.id',
'categories.position',
'categories.visible',
'categories.created_at',
'categories.updated_at',
'categories.title',
'photos.filename']);
Or you could...
Use the power of Eloquent
You only need to define the relationship (I assume you already have a Photo model) and this gets a lot easier
class Category extends Eloquent {
public function photos(){
return $this->hasMany('Photo', 'cover_id');
}
}
And then...
$data = Category::with('photos')->get();
And you will have the photos model nested inside the category models. Accessible like this:
foreach($data as $category){
foreach($category->photos as $photo){
echo $photo->filename;
}
}

I would rather do it this way:
// Just assuming a few variables for better understanding
$allCategories = Category::all();
foreach ($allCategories as $category) {
$photo = Photo::find($category->cover_id);
if ($photo) { // $photo!=null or isset($photo) - you can use anything
// photo is found do the additional processing
}
//proceed with your normal processing
}

Related

Conditionally CONCAT based on helper column data using ARRAYFORMULA in Google Sheets

I have 2 columns of names (Name 1, Name 2) which I would like to concat into a single column.
[CURRENT DATA SET] [FORMULA - CONCAT]
| A | B | | D |
| Name1 | Name2 | | Name1_Name2 |
| Name3 | Name4 | | Name3_Name4 |
| Name5 | Name6 | | Name5_Name6 |
This portion is working using my ARRAYFORMULA:
=ARRAYFORMULA(
IF(
ISBLANK(B4:B),
CONCAT(A4:A,B4:B),
CONCAT(A4:A,("_"&B4:B))
)
)
Here is the issue: Sometimes I need the CONCAT formula to put column B first, then Colum A (Example Name2_Name1).
Objective: The CONCAT formula needs to be conditional based on a helper column containing the list of valid name options.
Logic:
If helper column matches CONCAT, CONCAT ColumnA_ColumnB.
If helper column does not match CONCAT, ColumnB_ColumnA.
If still does not match, leave blank.
Expected Results using a helper column
[CURRENT DATA SET] [Helper Column] [EXPECTED RESULTS]
| A | B | | C | | D |
| Name1 | Name2 | | Name1_Name2 | | Name1_Name2 |
| Name3 | Name4 | | Name6_Name5 | | Name3_Name4 |
| Name5 | Name6 | | Name3_Name4 | | Name6_Name5 |
| Name7 | | | Name5 | | |
| Name5 | | | Name8 | | Name5 |
Is it possible to create an arrayformula to achieve these expected results?
Here is my Google Sheet: Click Here
See if this works for you:
=ArrayFormula(IFERROR(IFERROR(VLOOKUP(A4:A&IF(LEN(B4:B), "_"&B4:B,), D4:D, 1, 0), VLOOKUP(IF(LEN(B4:B), B4:B&"_",)&A4:A, D4:D, 1, 0))))

Populate a single google doc using all the data from a google sheet

I am trying to populate a google doc using all the data from a google sheet. What I'm trying to do is to generate a report based on the data in the sheet.
I will be submitting daily report using a google form.
The report will be submitted into the google sheet.
The report recorded in the sheet will be then auto populate the google doc (Only one google doc will be populated).
Currently I have found the way to populate the data in a google doc but it will be generating a new google doc for every row of data.
This is the code that I found
function autofill(e) {
var timestamp = e.values[0];
var name = e.values[1];
var report = e.values[2];
var templateFile = DriveApp.getFileById("Google Doc ID");
var templateResponseFolder = DriveApp.getFolderById("Folder for Google Doc");
var copy = templateFile.makeCopy(name + ',' + report, templateResponseFolder);
var doc = DocumentApp.openById(copy.getId());
var body = doc.getBody();
body.replaceText("{{Timestamp}}", timestamp);
body.replaceText("{{Name}}", name);
body.replaceText("{{Report}}", report);
doc.saveAndClose();
}
Record from Google Sheet
+-----------------+----------+----------+
|Timestamp |Name |Position |
+-----------------+----------+----------+
|3/2/2021 14:12:13|John Doe 1|Position 1|
+-----------------+----------+----------+
|3/2/2021 14:15:13|John Doe 2|Position 2|
+-----------------+----------+----------+
This is the ouput of the above code.
+------------------------+
| John Doe 1 |
| Position 1 |
| |
| |
| |
| |
| |
| |
| |
+------------------------+
John Doe 1, Position 1.docs
+------------------------+
| John Doe 2 |
| Position 2 |
| |
| |
| |
| |
| |
| |
+------------------------+
John Doe 2, Position 2.docs
It will make a new Google Docs document every time a new data is recorded in Google Sheet.
This is what I am trying to achieve
+------------------------+
| John Doe 1 |
| Position 1 |
| |
| |
| |
| |
| |
| Page 1 |
+------------------------+
| John Doe 2 |
| Position 2 |
| |
| |
| |
| |
| |
| Page 2 |
+------------------------+
Report.docs
I am trying to populate all the data recorded in Google Sheet in a single Google Docs which is Report.docs
Modified Script
Since you were calling var copy = templateFile.makeCopy(name + ',' + report, templateResponseFolder); this was making a copy of the file.
With this modification, the templateFile will be updated every time.
function autofill(e) {
var timestamp = e.values[0];
var name = e.values[1];
var report = e.values[2];
var templateFile = DriveApp.getFileById("Google Doc ID");
var body = templateFile.getBody();
body.replaceText("{{Timestamp}}", timestamp);
body.replaceText("{{Name}}", name);
body.replaceText("{{Report}}", report);
doc.saveAndClose();
}
If this is not what you mean, then perhaps you can share a sample spreadsheet with sample data, and what you would like the result to be.
Reference
makeCopy()

Simple join in Aqueduct

I'm newbie in a backend development and stuck with a simple request and ask for help.
I am trying to get a simple join:
select * from product a, product_barcode b
where a.productid = b.productid
Structure of the classes:
Product
class Product extends ManagedObject<product> implements product {}
class product {
#primaryKey
int productid;
String rusname;
String engname;
ManagedSet<Product_barcode> products;
}
Product_barcode
Class Product_barcode extends ManagedObject<product_barcode>
implements product_barcode {}
class product_barcode {
#primaryKey
int productid;
String barcode;
#Relate(#products)
Product product;
}
Request
#Operation.get()
Future<Response> getProducts() async {
final productQuery = Query<Product>(context)..join(set: (a) => a.products);
final res = await productQuery.fetch();
return Response.ok(res);
}
When i make a request I am getting error:
SELECT t0.productid,t0.rusname,t0.engname,t1.productid,t1.barcode,t1.product_productid FROM product t0 LEFT OUTER JOIN product_barcode t1 ON t0.productid=t1.product_productid
column t1.product_productid does not exist
What I am doing wrong? I do not have a column product_productid in my database
Update
Table structure
drugs=# \dt product_barcode
List of relations
Schema | Name | Type | Owner
--------+-----------------+-------+----------
public | product_barcode | table | druguser
(1 row)
drugs=# \d product_barcode
Table "public.product_barcode"
Column | Type | Collation | Nullable | Default
-----------+-------------------+-----------+----------+---------
productid | integer | | not null |
barcode | character varying | | not null |
Indexes:
"product_barcode_pk" PRIMARY KEY, btree (productid, barcode)
drugs=# \dt product
List of relations
Schema | Name | Type | Owner
--------+---------+-------+----------
public | product | table | druguser
(1 row)
drugs=# \d product
Table "public.product"
Column | Type | Collation | Nullable | Default
-------------------------+--------+-----------+----------+---------
productid | bigint | | not null |
rusname | text | | |
engname | text | | |
registrationdate | text | | |
dateofcloseregistration | text | | |
registrationnumber | text | | |
composition | text | | |
zipinfo | text | | |
producttypecode | text | | |
marketstatusid | text | | |
Indexes:
"product_pkey" PRIMARY KEY, btree (productid)

Rail Query includes + filter by column

I start in Ruby and Ruby on rails. I am trying to modify the access to this object (below) in base via the form and I will like to filter by the values that are in the table node_tags.
def map
......
nodes = Node.bbox(bbox).where(:visible => true).includes(:node_tags).limit(MAX_NUMBER_OF_NODES + 1)
.....
end
Probably on SQL request
SELECT * FROM nodes n INNER JOIN node_tags nt on n.node_id = nt.node_id where nt.k = 'alert' and nt.v = 'true'
Table nodes
| node_id | latitude | longitude | changeset_id | visible | timestamp | tile | version | redaction_id |
|---------|-----------|-----------|--------------|---------|-----------|------|---------|--------------|
| 11 | 473705641 | 3955487 | 11 | TRUE |
| 12 | 473705641 | 3955487 | 12 | TRUE |
table node_tags
| node_id | k | v |
|---------|-------|------|
| 11 | name | bob |
| 12 | alert | true |
If I understand right, you need to get sql as in your example by ORM (ActiveRecord).
Try this:
nodes = Node.where(:visible => true).join(:node_tags).where("node_tags.k = 'alert' and node_tags.v = 'true'")

Grouping in MDX Query

I am very newbie to MDX world..
I want to group the Columns based on only 3 rows. But, need join for 4th row also..
My query is :
SELECT
( {
[Measures].[Live Item Count]
}
) DIMENSION PROPERTIES parent_unique_name ON COLUMNS,
Crossjoin(
crossjoin(
[Item].[Class].&[Light],
[Item].[Style].&[Fav]
[Item].[Season Year].members),
[Item].[Count].children ) on rows
FROM Cube
Output comes as :
Light(Row) | FAV(Row) | ALL(Row) | 16(Row) | 2(col)
Light(Row) | FAV(Row) | ALL(Row) | 7(Row) | 1(col)
Light(Row) | FAV(Row) | 2012(Row) | 16(Row)| 2(col)
Light(Row) | FAV(Row) | 2011(Row) | 7(Row) | 1(col)
But, I want my output to be displayed as:
Light(Row) | FAV(Row) | ALL(Row) | | 3(col)
Light(Row) | FAV(Row) | 2012(Row) | 16(Row)| 2(col)
Light(Row) | FAV(Row) | 2011(Row) | 7(Row) | 1(col)
i.e., I want to group my first two rows such that there is no duplicate 'ALL' in 3rd column..
Thanks in advance
Try this - using the level name Season Year with the Attribute name Season Year will pick up every member without teh ALL member:
SELECT
( {
[Measures].[Live Item Count]
}
) DIMENSION PROPERTIES parent_unique_name ON COLUMNS,
Crossjoin(
crossjoin(
[Item].[Class].&[Light],
[Item].[Style].&[Fav]
[Item].[Season Year].[Season Year].members),
[Item].[Count].children ) on rows
FROM Cube
You can use this query if there is an All member on the [Item].[Count] hierarchy:
SELECT {[Measures].[Live Item Count]} DIMENSION PROPERTIES parent_unique_name ON COLUMNS,
Crossjoin(
Crossjoin([Item].[Class].&[Light], [Item].[Style].&[Fav]),
Union(
Crossjoin({"All member of [Item].[Season Year]"}, {"All member of [Item].[Count]"}),
Crossjoin(Except([Item].[Season Year].members, {"All member of [Item].[Season Year]"}), [Item].[Count].children),
) ON ROWS
FROM Cube

Resources