Check Existance Of Entry In Model Within View File using Yii - php

This might sound kind of basic (and it probably is), but I've been trying to get this for a few hours now and either I need a break from coding or it just wont budge.
I have an active record variable which brings database entries from a model:
$variable = Model::model()->findAll();
So I have $variable available in my view file and I want to check for the existence of a specific entry within the results. I am using the primary key of an entry available in the $variable, but I can't seem to get it working.
What is the correct way to check if a given entry is contained within that variable from the view file, not the controller?
PS: I do not want to iterate through the result set, it wouldn't be very efficient for my application.
Thanks.

If I got you right then:
Indeed its better not to have such pieces of code in a view file.
If you are forced to use CActiveRecord.fin*() methods, consider using findByPk($pk). If it returns null - no such record.
Consider having your models extending PcBaseArModel as that class has 'checkExists($pk)' method that looks natural in the check you need to perform. This base class has other goodies - check its documentation.

Try this code:
$data = Post::model()->findAllBySql("select * from tbl_post where id=".$data->id);
or
$post=Post::model()->find(array(
'condition'=>'postID=:postID',
'params'=>array(':postID'=>$data->id)
));

Related

How do i fetch data inside a controller using laravel

I just started learning laravel.
I don't know how can I fetch data inside a controller,
I want to use that data inside a controller to make more rules.
//Get Data From Database
$db = DonorDetail::where('donation_id', $paytmResponse['ORDERID'])->get();
$name = $db['donor_name'];
$email_id = $db['email_id'];
DonorDetail is my model to connect to my database.
I tried this code, but getting undefined error.
I'm trying to select only 1 row using the unique donation_id and use data of other columns of data inside my controller.
get returns a collection. You should use first to get the first result from your query:
DonorDetail::where('donation_id', $paytmResponse['ORDERID'])->first();
If no results were found, null will be returned, so you should also pay attention to that.
You only provided us with a small portion of your code, but it seems like you're doing a lot of things in a non-Laravel way. It's only natural because, as you mentioned, you're just starting with Laravel. My recommendation to you is to check out Laracast's free "Laravel From Scratch" course:
https://laracasts.com/series/laravel-6-from-scratch
It's by far the best resource for developers taking their first steps in Laravel (and it also has good resources for experienced developers).
Good luck!
you can use dd() to see the data.
dd($db);
However, If you want to fetch only first matching data, use following
$db = DonorDetail::where('donation_id', $paytmResponse['ORDERID'])->first();
$name = $db->donor_name;
$email_id = $db->email_id;

What is a simple process to define contain with find function

Care to put light to the subject. Issue is that when I do what ever to code I find that code does not go further to retrieve data from table Sectors and table courses. I have applied find() I use CakePHP 4.x to make clear that it is latest version of CakePHP called Strawberry. I also do not understand that why does my code get affected while I apply simple code structure to run my code.
Take a look at code snippet to run a simple find query with CakePHP Strawberry.
$Sectors is not defined but I need to know a way to define and apply $Sectors variable so that I have given value for relative table structure.
Table Does not load because of a problem I do not understand yet but guys help me out I'll update my code and make use of real code that is to determine a structure for code that will work for CakePHP Strawberry.
code:
$this->loadModel('Sectors');
$this->loadModel('Courses');
$Sectors = $Sectors->find('all')->contain('Sectors', 'Courses');
pr($sectors);
$this->contain(['Sectors', 'Courses']);
$this->set(compact('sectors'));
To retrieve data from table so that I get data relation from Sectors and Courses table.
error:
Call to a member function find() on null
Answer is simple but problem is CakePHP would keep single model with multiple query but not multiple model with single query.

How can I set routing conditions based on the Doctrine Entity specified by one of the parameters?

So I've got two Doctrine entities, let's call them Box and Item. A box contains multiple items. I want the URLs for viewing an item to look like this:
/box/{box_id}/item/{item_id}
Obviously I want to show a 404 error message if the item (specified by the item_id) does not belong to the box specified by the box_id in the URL. I could do this by adding a check in every action in the controllers, but then I'd have to write the same code many times.
I'm looking for a way to specify the requirement without having to scatter if statements (or function calls) throughout all my functions. I've read about the condition-field (yaml) that can be used to specify more complex conditions, but I'm not quite sure how I'd get a reference to a doctrine repository from there.
Is there another way to do this?
I could do this by adding a check in every action in the controllers, but then I'd have to write the same code many times.
No, this is what we use functions for. So that only one line is duplicated between every action that needs them, and the function holds reusable code.
All you need to do is write a function which takes an item_id and a box_id, and returns true or false depending on relation.

MVC PHP: Data manipulation in View loop or Controller loop (ie. 1 loop or 2 loops)

Something that has always bothered me is doing more than one loop to manipulate an array.
What I mean is, in the controller the data is fetched from the DB via a model. Lets say we are showing a list of users, and each user has a status (1,2,3 equates to verified, unverified, banned respectively). Within each iteration of the loop the status would be checked and displayed via another Db query (forget mysql joins in this example).
Now, would you do that in the controller within a loop, and then perform another loop in the view with all the data already fetched and pre-formed ready for display (therefore resulting in 2 loops).
--OR--
Would you just do it in the view therefore resulting in the one loop but with model calls from the view. I understand that this is ok in the strict MVC pattern but its frowned upon generally.
It seems silly to loop twice but then its tidier as all the data manipulation is kept within the controller.
I would do that nor in the view or the controller but on the model.
I explain :
Your controller's job is to retrieve the expected user list, check ACL, etc...
Your view's job is to present this data in an elegant form
Your Model job's in to fetch/store data from Database and ensure integrity. Userstatus is a model too for me.
My configuration make this pretty easy, I use mustache (Php port) for view, which allow me to call methods from my models directly in view. I wrote my own ORM for my models, that way I have wrappers.
Such code would look like that for me :
// Controller
$template = new Template('pages/users.html');
$template->users = mUser::find(); // return array of mUsers instances
echo $template->render();
// View
{{#users}} <!-- For each user -->
{{getName}} has status {{#getStatus}}{{getStatusName}}{{/getStatus}}<br />
<!-- getStatus is a method from mUser model, that return a mUserStatus instance -->
{{/users}}
/* More explain on the view syntax
{{name}} = $user->getName() (return string)
{{getStatus}} = $user->getStatus() (return instance of mUserStatus);
{{statusName}} = $user->getStatus()->getStatusName();
*/
You may want to have request caching for each model instances in request level so that you never runs a request twice times if not needed.
That seems more natural to me than to delegate it to controller. I try to put business intelligence on controllers, there is no need for intelligence nor programmer intervention to retrieve a status name for each user.
I Hope it help.
In my opinion logic that manipulates the data you're returning, should be located in the controller. Logic that manipulates the representation of your data can be located in the view.
So I would go for the second option.
But, as you pointed out yourself this is a choice of implementation.
Also note that multiple round trips to your DB are bad for performance. Your example is a typical n+1 problem, meaning that you have 1 'top' select query and then N more queries for each row in your first result set. If you encounter such a problem always try to solve them on the DB level.
Another note I would like to add is that in your example you're storing status explanations in the DB. If you want to provide your applications in other languages, this might prove to be a problem. But this is beyond the scope of your question :)
Doing two loops is the clean way. That is what I would do for most cases, but I think there is no gerneral answer to this. Like if you have a lot a data and performance gets an issue it would be better to forgett about MVC and just use one loop.
A third way would be to use a helper function you can call from the view. Now that I think about it... that would probably be the best way.

Where to put certain logic in CakePHP

I've recently started to rewrite a project I did a few years ago using CakePHP. I'm trying to do everything 'right' this time, so maybe someone get give me a a pointer on doing to the following:
I'm showing a simple table from a table using Model->find('all') in the View. There are two boolean fields in this table, that together make up something I need to show to a user. So: 0x0 = 'A', 1x0 = 'B', 0x1 = 'C', 1x1 = 'D'. Where should I put this logic? I've been thinking about the following methods:
The view
A View helper
The controller
Something in the Model so that Model->find('all') outputs this value (is that even possible?)
This task might seem trivial, but I think it might learn me getting this project organized and maintainable from the start.
Thanks!
Well, it depends on the type of logic for making up final table (is it presentation or business?).
Imagine you add new type of UI, for example command line interface. How would you show your table there? The data passed to View has to be same for both HTML and console presentations. So the logic which is responsible for preparing that data - is business logic and it should be placed in Model. The logic responsible for displaying the data should be placed in View (maybe in view helper if it's used more than once).
And never place this kind of logic in Controller.
If it's something you're going to use all over the place I would put it in the model. You can either put a method on the model that gives that value back or loop over all the rows you've retrieved in an afterFind callback and set it as a proper field.
I put this kind of logic in the view if it is something that is going to determine rendering style. In that way, the designer has maximum access and can style accordingly.
On the other hand, if the two columns only exist for convenience in datamodelling, put it in the model. The designer shouldn't even be aware of other possibilities!
In the controller! The methods from the model comes in the controller. The view is just for output( like HTML UI programming.)

Categories