Retrieving data from database and passing it as instance of entity - php

I'm trying to pass id from query from one database table to another table to which is related.
But, since they are related I have to pass it as instance of the entity(class) to which is related.
This is error I got:
Argument 1 passed to App\Entity\KeywordRating::setKeywordId() must be an instance of App\Entity\Keywords, integer given, called in C:\xampp\htdocs\ratingAPI\src\Service\KeywordRatingService.php on line 26
This is my code:
public function insertRating($params, ObjectManager $manager, KeywordsRepository $keyRep, ProvidersRepository $provRep)
{
$keywordId = $keyRep->checkKeyword(strtolower($params['keyword']))->getId();
$providerId = $provRep->checkProvider($params['provider'])->getId();
$rating = new KeywordRating();
$rating->setKeywordId(<Keywords instance> $keywordId);
$rating->setProviderId(<Providers instance> $providerId);
if($params['attr'] === 'rocks')
{
$rating->setRocksRating($params['rating']);
$rating->setSucksRating(0);
} else
{
$rating->setRocksRating(0);
$rating->setSucksRating($params['rating']);
}
$rating->setRocksVotes(10);
$rating->setSucksVotes(8);
$rating->setSumVotes(18);
$rating->setScore(2.50);
$manager->persist($rating);
$manager->flush();
}
This is sql query:
public function checkKeyword($keyword)
{
return $this->createQueryBuilder('k')
->where('k.keyword_name = :val')
->setParameter('val', $keyword)
->getQuery()
->getOneOrNullResult();
}
checkProvider() is the same, only different parameters.
How do I do that?

Assuming you have a namespace called Entities where you have all your entities classes, you can try something like this:
$entityManager = $this->getDoctrine()->getManager();
$queryBuilder = $entityManager->createQueryBuilder();
$queryBuilder->select('keyword')
->from('App\Entity\Keywords', 'keyword')
->where($queryBuilder->expr()->eq('keyword.keyword_name', $queryBuilder->expr()->literal($keyword)));
$result = $queryBuilder->getQuery()-> getOneOrNullResult();
return $result;

Related

Property [vegan] does not exist on this collection instance. Laravel

I'm trying to show a title based on whether a specific column in my table is 1 or 0. In my Controller I have (edited out some irrelevant code):
public function show(Company $id){
$vegan = Company::find($id);
$vegetarian = Company::find($id);
return view('allProducts')->with([
'vegan' => $vegan,
'vegetarian' => $vegetarian,
]);
}
and in my view:
#if($vegan->vegan == 1)
<h3 class="text-center">Vegan</h3>
#endif
However I get error message
ErrorException (E_ERROR)
Property [vegan] does not exist on this collection instance. (View: C:\xampp\htdocs\EdenBeauty\resources\views\allProducts.blade.php)
Ive tried the following but I get errors every time:
#if($vegan[0]->vegan == 1)
This gives undefined offset errors
The problem is you're missing first() after your queries:
$vegan = Company::find($id)->first();
$vegetarian = Company::find($id)->first();
In this line, you're injecting a Company into your show method via URL parameter:
public function show(Company $id){ ... }
At that point, $id is either a Company instance or null. Calling $vegan = Company::find($id) doesn't make any sense, and I'm actually surprised you don't get an error at that point in the code.
Also, if you're using injection, name the variable correctly Company $company to avoid confusion, and reference later:
public function show(Company $company){
$vegan = $company;
$vegetarian = $company;
// Or `$vegan = Company::find($company->id);`
// (This is redundant, but demonstrates the syntax)
return view("...")->with(...);
}
Alternatively, remove injection and query:
public function show($id){
$vegan = Company::find($id); // Note can use use `firstOrFail()`, etc.
$vegetarian = Company::find($id);
...
}
Either way, find() does not return a Collection, so $vegan->vegan would not return "Property [vegan] does not exist on this collection instance.", but something about your usage is treating it that way.

How to save update from relationships model Laravel 5.3

I want to save an update from One to Many relation model in Laravel 5.3, but I have this error.
FatalThrowableError in HasOneOrMany.php line 221:
Type error: Argument 1 passed to Illuminate\Database\Eloquent\Relations\HasOneOrMany::save() must be an instance of Illuminate\Database\Eloquent\Model, instance of Illuminate\Database\Eloquent\Collection given, called in C:\xampp\htdocs\wismasejahtera\app\Http\Controllers\JurnalController.php on line 129
Here is my Jurnals model:
public function djurnals()
{
return $this->hasMany('App\DJurnals', 'jurnal_id');
}
And here is my Djurnals model:
public function jurnals()
{
return $this->belongsTo('App\Jurnals');
}
public function rekenings()
{
return $this->belongsTo('App\Rekenings');
}
And here is my Controller:
$jurnal = Jurnals::find($id);
$jurnal->no_jurnal = $request->no_jurnal;
$jurnal->tgl_jurnal = $tglJurnalFix;
$jurnal->keterangan = $request->keterangan;
$jurnal->save();
//ini Array
$kode_rekening = $request->kode_rekening;
for($i=0; $i<count($kode_rekening); $i++){
$djurnal = Djurnals::where('jurnal_id', $id)->get();
$djurnal->kode_rekening = $request->kode_rekening[$i];
$djurnal->keterangan_rekening = $request->keterangan_rekening[$i];
$djurnal->d_k = $request->d_k[$i];
$djurnal->jumlah = $request->jumlah[$i];
if($request->d_k[$i] == 'D'){
$saldoRekKas = Rekenings::where('kode_rekening', 'like', '111%')
->increment('saldo', $request->jumlah[$i]);
}
else{
$saldoRekKas = Rekenings::where('kode_rekening', 'like', '111%')
->decrement('saldo', $request->jumlah[$i]);
}
$jurnal->djurnals()->save($djurnal);
}
return Redirect::to('jurnal');
And the error is in this row in Controller:
$jurnal->djurnals()->save($djurnal);
When I use this way to save a new jurnal and djurnal, it works correctly. But, When I try to save an update, it show an error. How can I save this update data to database? Anyone can help me?
Since you use the jurnal_id to get the Djurnals model, you need to save it directly.
Replace
Djurnals::where('jurnal_id', $id)->get();
With
Djurnals::where('jurnal_id', $id)->first();
Replace
$jurnal->djurnals()->save($djurnal);
With
$djurnal->save();
$jurnal->djurnals()->save($djurnal); Should be used only when saving a newly created model.

BadMethodCallException in Macroable.php line 81:Method update does not exist

I an developing a page to create, update, delete and view an event in which there is error while updating the event. There is a event table and a event_collection table. In that event_collection table there is event_id which is id of an event and a collection_id which is from other table collection.
When i create an event, all the data gets stored in event table except the collection one. in the collection table data gets stored in one by one manner like if I check 2 items in collection, it will generate 2 ids with same event_id and 2 collection_ids.
There is problem in update, when i try to update the code, it gives me error as
BadMethodCallException in Macroable.php line 81:
Method update does not exist.
Update method is:
public function update(EventRequest $request, $id)
{
$event = Event::findOrFail($id);
$input = $request->all();
$input['days_of_week'] = serialize(Input::get('days_of_week'));
$query = $event->update($input);
$checkbox_selection = Input::get('agree');
$choosen_checkbox = $id;
$collection_event = EventCollection::where('event_id',$choosen_checkbox)->get();
// return $collection_event;
if (!is_null($checkbox_selection)) {
foreach ($checkbox_selection as $collection) {
// $collection_id = $id;
foreach($collection_event as $k){
// return $k;
if($k->event_id == $choosen_checkbox){
$data = $request->all();
$data['event_id']= $choosen_checkbox;
$data['collection_id'] = $collection;
$collection_event->update($data);
}
}
}
}
My store method is:
public function store(Request $request)
{
$checkbox = Input::get('days_of_week');
$checkbox_selection = Input::get('agree');
// return $checkbox_collection;
$input = $request->all();
$input['days_of_week'] = serialize($checkbox);
$query = Event::create($input);
$event_id = $query->id;
$pro_id = $query->provider_org_id;
/*For the checkbox selection, if they are multiple store each separately*/
if (!is_null($checkbox_selection)) {
foreach ($checkbox_selection as $collection) {
$collection_id = $query->id;
if($collection_id){
$data = $request->all();
$data['event_id']= $collection_id;
$data['collection_id'] = $collection;
$create_collection = EventCollection::create($data);
}
}
}
return view('event.pic_upload',compact('event_id','pro_id'));
}
Store method works properly! Can someone please tell any solution? I am badly stucked in this.
I do not think the 'update' method works on collections.
This line will return a collection
$collection_event = EventCollection::where('event_id',$choosen_checkbox)->get();
You do not want a collection, rather a query. As given in the docs:
`App\Flight::where('active', 1)
->where('destination', 'San Diego')
->update(['delayed' => 1]);`
Try removing the '->get()' from the statement.

Doctrine Query Builder Result: not looping correctly

I'm not sure if it's that I'm not doing correctly but this is giving me an error:
I have 2 Entities: Task and TaskUser. They are connected by a onetoMany.
What I want to do is this:
foreach($tasks as $task){
echo $task->getTitle;
echo $task->getTaskUser()->getFirstName();
}
This is my query in the Task Repository:
public function findTasksByUsers($user = false)
{
if($user){
$qb = $this->_em->createQueryBuilder();
$qb
->select('t', 'tu')
->from('\Entities\Task', 't')
->leftJoin('\Entities\TaskUser', 'tu', \Doctrine\ORM\Query\Expr\Join::WITH, 't.id = tu.task')
->where('tu = :user')
->setParameter('user', $user)
->orderBy('t.createDate', 'DESC');
return $qb->getQuery()->getResult(\Doctrine\ORM\Query::HYDRATE_OBJECT);
}
}
When I do this loop:
$tasks = $this->em->getRepository('\Entities\Task')->findTasksByUsers($user);
foreach($tasks as $task){
echo $task->getTitle();
}
I get the the title of the first task, and then an error like this:
Title of first task
Fatal error: Call to undefined method Entities\TaskUser::getTitle() in D:\sites\db\application\controllers\TasksController.php on line 35
Any idea why this is happening? Thanks!
$qb->select('t', 'tu')
the issue is here as you're selecting both entities.
If you want only Task entity modify your DQL as follows
$qb->select('t')
However, to me, you could only procede that way (in your controller; if you aren't into controller, use DI to access entity manager)
//retrieve all TaskUser object
$em = $this->getDoctrine()->getManager();
$tu_repo = $em->getRepository('YourBundleName:TaskUser');
$tu_array_collection = $tu_repo->findBy(array('user'=>$user));
foreach ($tu_array_collection as $tu) {
$first_name = $tu->getFirstName();
foreach ($tu->getTasks() as $task) {
echo $first_name;
echo $task->getTitle();
}
}
of course you may need to adapt your code with right findBy array, and with correct methods from TaskUser entity

Laravel Eloquent Save Item

When I try to save an item in Laravel it says the following.
Call to undefined method Illuminate\Database\Query\Builder::save()
I have followed the documentation, and i can delete items fine just not update. Is there anything wrong with my code?
public function publishedMain($id, $state){
$userId = Auth::user()->id;
$userAdmin = Auth::user()->admin;
if($userAdmin == "0"){
$clients = Clients::whereRaw('id = ? and parent = ?', array($id, $state));
$clients->active = $state;
$clients->save();
die('not admin');
}else{
$clients = Clients::whereRaw('id = ?', array($id));
$clients->active = $state;
$clients->save();
die('admin');
}
}
Many Thanks
Brent
You call the save() method on the query builder, not on your model.
You're missing the ->first() piece:
$clients = Clients::whereRaw('id = ? and parent = ?', array($id, $state))->first();
Of course, this will get the first client, so naming the variable $clients makes not much sense.
You shall also check if your $clients variable is not null, in which case it didn't find anything.
(btw, your model should be called Client, not Clients)

Categories