Symfony insert into a table, all colums foreign key - symfony

I want to insert data into a middle table Builds_Perks with columns idBuild and idPerks. The problem is with idPerks, I take the id from some checkbox and when I want to isnert those id the following error appears:
Argument 2 passed to App\Entity\BuildsPerks::__construct() must be an instance of App\Entity\Perks, int given...
This is part of the code where I take the checkbox id to INSERT them:
$idAllPerks = $request->get('chk');
foreach($idAllPerks as $idPerk) {
$idPerkInt = (int) $idPerk; // string into int
$newBuildPerk = new BuildsPerks(
$usuBuild,
$idPerkInt
);
$this->getDoctrine()->getManager()->persist($newBuildPerk );
}
Thanks.

The error message is very clear. It expects to receive an object of type Perks but you are giving the ID of that object instead of the object itself. This might work.
$idAllPerks = $request->get('chk');
foreach($idAllPerks as $idPerk) {
$em = $this->getDoctrine()->getManager();
$perk = $em->getRepository(Perks::class)->find((int) $idPerk);
$newBuildPerk = new BuildsPerks(
$usuBuild,
$perk
);
$em->persist($newBuildPerk );
}

Related

get count with hasMany not working yii2

I have CLub model (clubs) hasMany with User model like
Club n-n User
and I have UserClub model with columns: id, club_id, user_id, etc
In Club model
public function getCountUsers()
{
return $this->hasMany(UserClub::className(), ['club_id'=>'id'])->count();
}
I wanna count all User on Club as code:
$query = Club::find()
->joinWith(['countUsers']);
// ->with('countUsers');
->all();
so it is not working and throwing an error
Club has no relation named \"countUsers\"."
Because it isn't a relation as it does not return a model object or an array of model objects, instead you are using ->count() that makes it return a string that contains the total count for the user against the club.
If you are looking to get a count for the users against all the Clubs you can use the currently defined relation like $club->countUser see below.
$clubs=Club::find()->all();
foreach($clubs as $club){
echo $club->countUser;
}
or change the relation to
public function getCountUser(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
and use it like
$clubs=Club::find()->all();
foreach($clubs as $club){
echo count($club->countUser);
}
or like below
$clubs=Club::find()->all();
foreach($clubs as $club){
echo $club->getCountUser()->count();
}
EDIT
You are actually trying to transform the following query using ActiveRecord as far as I understood from the discussion.
SELECT clubs.id, count(user_clubs.id) as total
FROM
clubs
left join user_clubs on clubs.id = user_clubs.club_id
group by clubs.id
if that is correct you can use the following
Clubs::find ()
->alias ( 'c' )
->select ( [ new \yii\db\Expression ( 'c.[[id]], count(uc.[[id]]) as total' ) ] )
->leftJoin ( '{{%user_clubs}} uc' , 'uc.club_id=c.id' )
->groupBy ( 'c.id' )
->all ();
Note : You have to do one more thing you have to add a public property $total inside your Club model and add it to safe rules, because you are selecting the count as an alias total and until unless you define it inside the model the result set won't show you the count, so add the following inside the Club model.
public $total;
under rules
[[other fields...,'total'] , 'safe' ] ,
EDIT2
For some reason, I have a feeling that you are trying to count by specifying a relation instead of specifying the ->leftJoin () with the table user_clubs in the query.
If that is so then you have to change your relation getUserCount() you should better give a meaningful name that describes it. i would rename it to getClubUsers()
public function getClubUsers(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
After this, you still have to declare a public property $total as I described before inside your Club model, and add it to safe rules.
Now you can write your query in the following way
Clubs::find ()
->alias ( 'c' )
->select ( [ new \yii\db\Expression ( 'c.[[id]], count(cu.[[id]]) as total' ) ] )
->joinWith( ['clubUsers cu'] )
->groupBy ( 'c.id' )
->all ();
You can do this with join, in my case i get users who have more than 0 referrals.
$users = User::find()->with('referrals')
->from(User::tableName() . ' t')
->join('left join',User::tableName().' r','r.Deeplink = t.ReferralID')
->select('t.*,count(r.ID) as ct')
->groupBy('t.ID')
->andFilterHaving(['>','ct',0])
->all();
Hi your relation is correct check you error Club has no relation named \"countUsers\"."
Means you are calling a relation which not exist :
change query like this, Relation name should be in Club Model
public function getCount(){
return $this->hasMany(UserClub::className(), ['club_id'=>'id']);
}
$clubs=Club::find()->all();
foreach($clubs as $club){
echo count($club->getCount);
}
$query = Club::find()
->joinWith(['count']);
// ->with('countusers');
->all();
If you want count just do like this .
Load the Club model .
$club_model = Club::find()
$count = club_model->count;

Symfony 3 one-to-many, get parent with all children if one child satisfy the codition

I have these two tables
I want to get all products(with all the children) that have at least one child with log_id = 13. Let's say I have the following rows in eorder_product_config table:
The function that retrieves the products looks like this:
public function getProducts($logId){
$q = $this
->createQueryBuilder('p')
->select('p', 'pc')
->where('pc.logisticStatus = :logId')
->setParameter('logId', $logId)
->getQuery();
return $q->getResult();
}
This will get the product(id = 18) with only 2 children(id = 46,48) in the productConfigs collection and I want have all 5 children if there is at least one that has log_id = 13.
I've found a workaround using subqueries:
public function getProducts($logId){
// search for configs that have log_id = 13
$subQuery = $this->createQueryBuilder('pp')
->select('DISTINCT pp.id')
->leftJoin('pp.productConfigs', 'ppc')
->leftJoin('ppc.logisticStatus', 'pls')
->where('ppc.logisticStatus = :logId');
//->andWhere('ppc.id = p.id'); // used for EXIST query method
// main query
$q = $this->createQueryBuilder('p');
$q->select('p', 'pc');
$q->leftJoin('p.productConfigs', 'pc')
// inject subquery, check to see if current product is in
// the subquery result
$q->where($q->expr()->in('p.id', $subQuery->getDQL()));
//$q->where($q->expr()->exists($subQuery->getDQL()))
$q->setParameter('logId', $logId);
return $q->getQuery()->getResult();
}
***I've seen that using the EXIST query does't work as it should that's why I choose the IN query. But in the raw sql query they both return same results.

How to update temp table data during run time AX 2012

I'm new to X++ development. I'm trying to add a field in Vendor aging report. It was done as excepted.
my problem is updating the field value during run time.
Scenario,
We have a Invoice field contain "AA_BBBBBB". What I need to do is I need to split the value as AA, BBBBBB and update BBBBBB to invoice field and AA to new field (Invoice type).
Issue,
Once i got the values to temptable VendAgingReportTmp in the method VendAgingReportDP\insertVendAgingReportTmp, I'm tried to update the above scenario but code is not selecting the records from VendAgingReportTmp. Can someone help me to get this thing done.
In VendAgingReportDP class insertVendAgingReportTmp the last line of standard code is vendAgingReportTmp.insert();
If your code is before vendAgingReportTmp.insert(); You do not need to perform the update. If you put vendAgingReportTmp.update(); before vendAgingReportTmp.insert(); you get that error.
Put your code inside //YourCode and //YourCode END withhout vendAgingReportTmp.update();
Example:
/// <summary>
/// Inserts records into the temporary <c>VendAgingReportTmp</c> table.
/// </summary>
/// <param name="_reverseAmountsAndHeadings">
/// A boolean value which indicates whether the column values should be reversed.
/// </param>
private void insertVendAgingReportTmp(boolean _reverseAmountsAndHeadings)
{
vendAgingReportTmp.AsOfDate = strFmt("#SYS84682", date2StrUsr(contract.parmZeroDate(), DateFlags::FormatAll), contract.parmDateTransactionDuedate());
vendAgingReportTmp.HeadingAccount = strFmt("#SYS24500");
vendAgingReportTmp.HeadingName = strFmt("#SYS7399");
switch (contract.parmDateTransactionDuedate())
{
case DateTransactionDuedate::DocumentDate : vendAgingReportTmp.HeadingDate = "#SYS2587";
break;
case DateTransactionDuedate::TransactionDate : vendAgingReportTmp.HeadingDate = "#SYS67";
break;
case DateTransactionDuedate::DueDate : vendAgingReportTmp.HeadingDate = "#SYS14588";
break;
default : vendAgingReportTmp.HeadingDate = "#SYS14588";
break;
}
if (_reverseAmountsAndHeadings)
{
this.setVendAgingReportTmpInReverse();
}
else
{
this.setVendAgingReportTmp();
}
vendAgingReportTmp.TransDate = tmpAccountSum.TransDate;
vendAgingReportTmp.InvoiceId = tmpAccountSum.InvoiceId;
vendAgingReportTmp.Voucher = tmpAccountSum.Voucher;
vendAgingReportTmp.AccountNum = tmpAccountSum.AccountNum;
vendAgingReportTmp.Name = vendTable.name();
vendAgingReportTmp.VendAccount = tmpAccountSum.AccountNum;
vendAgingReportTmp.Txt = tmpAccountSum.Txt;
vendAgingReportTmp.Balance = 100;
vendAgingReportTmp.CurrencyCode = tmpAccountSum.CurrencyCode;
vendAgingReportTmp.VendGroup = vendTable.VendGroup;
//YourCode
//...
//...
//...
//YourCode END
vendAgingReportTmp.insert();
}
I got a solution by adding below,
Added InvoiceType field to temptable VendTmpAccountSum Since this is declared as global variable.
Updated our custom Invoice type to InvoiceType field in VendTmpAccountSum.
Then insert the whole data to VendAgingReportTmp from VendTmpAccountSum table by using insert_recordset to increase the performance.
Thanks,

drupal_map_assoc($array)

function _ahah_example_get_first_dropdown_options() {
$stid = oci_parse($conn, "SELECt code,descr1 FROM dbtest.regions");
oci_execute($stid);
$region= array();
while (($row = oci_fetch_array($stid, OCI_ASSOC))) {
$region[$row['CODE']]= $row['DESCR1'];
}
$region['']='Select';
oci_free_statement($stid);
oci_close($conn);
return drupal_map_assoc($region);
}
but it returns the key and the value equal I need the original key to be returne cause im using it's value in a javascript function?anyone would know how to return the original Key?
From your code, you should be able to skip drupal_map_assoc and just return $region. Give that a try and see if you like the results.
Reference http://api.drupal.org/api/drupal/includes--common.inc/function/drupal_map_assoc/6

Linq2XML missing element

How do I modify the query below to properly handle the case where the "Summary" element is missing from one of the articles? Now when that happens I get an "Object reference not set to an instance of an object."
var articles = from article in xmlDoc.Descendants("Article")
select new {
articleId = article.Attribute("ID").Value,
heading = article.Element("Heading").Value,
summary = article.Element("Summary").Value,
contents = article.Element("Contents").Value,
cats = from cat in article.Elements("Categories")
select new {
category = cat.Element("Category").Value
}
};
The problem is that article.Element("Summary") returns null if the element is not found, so you get a NullReferenceException when you try to get the Value property.
To solve this, note that XElement also has an explicit conversion to string. This won't throw if the XElement is null - you will just get a null string reference.
So to solve your problem you can change this:
summary = article.Element("Summary").Value,
to this:
summary = (string)article.Element("Summary")

Resources