Property [participants_count] does not exist but exists and can be dumped - laravel-8

I have 2 tables, evenements and participants, represented by 2 models Evenement and Participant.
Those entities are belongsToMany related, so I have a third table evenement_participant following Laravel's naming conventions, and inside are foreign evenement_id and participant_id columns.
I'm able to retrieve the relationship and I can
dd($evenement->participants)
which gives me a collection of participants.
In my controller, I have this db call:
$evenements = Evenement::withCount(['participants' => function($query) {
$query->where('is_active', 1);
}])
This withCount generates a participants_count attribute for each evenement.
In my blade view, there is a for-each loop on the evenements collection, and somewhere I do this:
$evenement->participants_count
and I face this error:
Property [participants_count] does not exist on this collection
instance.
However, if instead I do the following in the same blade view
#dd($evenement->participants_count)
it dumps me the count.
I dropped all the evenements to keep just one for testing, and I still have the same error.

Sorry, made a typo in a condition inside my blade loop

Related

Displaying data from a normalised m-m relationship

I have have 2 tables, ServiceProvider , Entity. There is a m-m relationship between them so I created a link table spEntity which contains the foreign keys from both the other tables.
I have backpack working fine on the 3 tables separately, I use the relationship type on the spEntity CRUD to show the names from the other 2 tables and this all works fine.
However, what I would like to do is when the ServiceProvider record is being created
show a list of all the entities
allow the user to select one and then when the save button is pressed
create the spEntity record.
I have tried
protected function setupCreateOperation()
{
CRUD::setValidation(ServiceProviderRequest::class);
CRUD::field('ServiceProviderName');
CRUD::field('ServiceProviderEmailAddress');
CRUD::field('ServiceProviderDescription');
CRUD::addfield(['name'=>'Entity',
'type'=>'relationship',
'attribute' => 'EntityName',
'pivot'=>true,
'relation_type'=>'belongstomany'
]);
}
but I get the error :
BadMethodCallException PHP 8.1.7 9.19.0
Method Backpack\CRUD\app\Library\CrudPanel\CrudPanel::relationAllowsMultiple does not exist.
Table relations
Is this possible?
Try updating laravel-backpack/CRUD because seems to be an old bug.
Partial solution.
The problem was in my model definition. I need to add in the m-m relationship there.
Model
public function entities()
{
return $this->belongsToMany(Entity::class,'SPEntity','Entity_idEntity','ServiceProvider_idServiceProvider')
->withPivot('idSPEntity')
->withTimestamps();
}
then in the Crud controller
CRUD::addfield(['name'=>'entities',
'type'=>'select2_multiple',
'attribute' => 'EntityName',
'pivot'=>true,
'relation_type'=>'belongstomany'
]);
this now displays the field correctly and I can add further entities to the Service Provider.
However the information is not saved.

Sulu: Entity has no field or association error

I'm following Sulu example here: https://github.com/sulu/sulu-workshop/
trying to set translations for custom entity type.
My entity file has getter for field "home_team" defined like:
/**
* #Serializer\VirtualProperty(name="home_team")
*/
public function getHomeTeam(): ?string
{
$translation = $this->getTranslation($this->locale);
if (!$translation) {
return null;
}
return $translation->getHomeTeam();
}
So field is not actually part of that entity, but of it's translation entity since it suppose to be translatable.
When I try to create new object of that entity type it works well. I can see in database that field values are stored well and I don't get any error.
But on overview page instead of list of all objects I get error:
[Semantical Error] line 0, col 73 near 'home_team AS': Error: Class App\Entity\MatchEvent has no field or association named home_team
Any idea what could be wrong here?
If you wanna see the translation in the listView you have to create a real translationEntity, like in the workshop project. In this post it is already explained, how to translate a custom entity correctly.
If you have already created your translationEntity you have to configure the relation of the translation to your main entity via a join. Here is an example in the workshop for this configuration.
Sulu uses optimised queries to create the list-object directly from the database. So the entity itself does not get hydrated or serialised for performance reasons. Thus your virtualProperty is never executed.

can't get relation's name via listdata

I am not sure why I can't get the columns from my other tables via my relations. I was thinking is it because of my scope? After i had a default scope in my models, everything seems to be out of place, even if i use resetscope() at some places. Some sections I can't get to my relation columns; when that happens, I'd have to use Model::model->findbypk(n)->name.. that doesn't look pretty.
the id shows if i don't have the relations, but the name is blank when i put the relation name.
CHtml::listData(Model::model()->findAll(),'product_id','main.product_name'),
my model defaultscope is pretty basic:
return array(
'condition'=>'store_id1=:store_id OR store_id2=:store_id' ,
'params' => array(':store_id' => $store_id)
);
You can change the way you use your model like below:
Model::model()->with('main')->findAll();

Invalid index N for this SqlParameterCollection with Count=N only when associated table has null record

I have a rather complex entity which will not save when a particular database table is missing a record. When the record exists the entity saves correctly. When the record does not I receive the exception:
Invalid index N for this SqlParameterCollection with Count=N
After reading a bunch of solutions found via Google and the most closely related questions on Stack Overflow:
What's causing “Invalid index nn for this SqlParameterCollection
with Count=nn” when a column is Null in the database?
Invalid Index n for this SqlParameterCollection with Count=n” OR “foreign key
cannot be null
I believe my issue has to do with the way I have my mapping files setup. The Customer entity has reference to the Person entity. Person maps to a table which we have read, but not write access to. It is when a record for the Person entity does not exist that I generate the exception. If the record exists no issue. I've set the reference to Person from customer to Nullable(). I have also double checked to ensure I do not have a property mapped twice from either entity.
Here is what I feel is the pertinent mapping information, but can provide more as needed:
Customer
//more mapping code...
References(x => x.Person, "snl_id").Nullable();
//more mapping code...
Person
//more mapping code...
ReadOnly();
Id(x => x.SnlId).Column("SNL_ID");
//more mapping code...
To further complicate matters we have some painful code to make NHibernate perform better when Person does not exist. I am not sure it applies here, but thought it pertinent enough to include in my question. We are using the below code because without it the NHibernate JIRA will create tons of queries. This solution is outlined in this Stack Overflow answer.
Customer's person property
public virtual Person Person
{
get
{
try
{
var snlId = per.Name;
return per;
}
catch
{
return null;
}
}
set
{
per = value;
}
}
private EPerson per;
What am I missing in my mappings that would cause this exception? Is there another piece of this problem that I am not seeing?
While Scott's solution of removing the snl_id property from the Customer class fixes the issue it causes problems that I cannot get around-- the snl_id can exist in the Customer table even there is not a corresponding Person table record. Since that is the case there are times when I will need access to the snl_id when I cannot get to it via the associated Person property.
I considered several alternative solutions but settled on creating a view of the Customer table including the Customer table primary key and the snl_id from the customer table. Then mapping that property via a join to the view.
Join("v_cust_id_snl_id", j => j.KeyColumn("cust_id").Map(x => x.SnlId, "snl_id")
This change allowed me to have my cake and eat it to. I was able to keep the SnlId property on customer, but no longer throw the exception when saving.
Do you have the snl_id referenced as a property in Customer as well as being the primary key for the child object? If so, this is causing the error you are receiving. Remove the property from Customer and use Person to get the value.

EF: How to do effective lazy-loading (not 1+N selects)?

Starting with a List of entities and needing all dependent entities through an association, is there a way to use the corresponding navigation-propertiy to load all child-entities with one db-round-trip? Ie. generate a single WHERE fkId IN (...) statement via navigation property?
More details
I've found these ways to load the children:
Keep the set of parent-entities as IQueriable<T>
Not good since the db will have to find the main set every time and join to get the requested data.
Put the parent-objects into an array or list, then get related data through navigation properties.
var children = parentArray.Select(p => p.Children).Distinct()
This is slow since it will generate a select for every main-entity.
Creates duplicate objects since each set of children is created independetly.
Put the foreign keys from the main entities into an array then filter the entire dependent-ObjectSet
var foreignKeyIds = parentArray.Select(p => p.Id).ToArray();
var children = Children.Where(d => foreignKeyIds.Contains(d.Id))
Linq then generates the desired "WHERE foreignKeyId IN (...)"-clause.
This is fast but only possible for 1:*-relations since linking-tables are mapped away.
Removes the readablity advantage of EF by using Ids after all
The navigation-properties of type EntityCollection<T> are not populated
Eager loading though the .Include()-methods, included for completeness (asking for lazy-loading)
Alledgedly joins everything included together and returns one giant flat result.
Have to decide up front which data to use
It there some way to get the simplicity of 2 with the performance of 3?
You could attach the parent object to your context and get the children when needed.
foreach (T parent in parents) {
_context.Attach(parent);
}
var children = parents.Select(p => p.Children);
Edit: for attaching multiple, just iterate.
I think finding a good answer is not possible or at least not worth the trouble. Instead a micro ORM like Dapper give the big benefit of removing the need to map between sql-columns and object-properties and does it without the need to create a model first. Also one simply writes the desired sql instead of understanding what linq to write to have it generated. IQueryable<T> will be missed though.