How to show only a specific amount of data on a table - mysql

I made a column to my 'users' table called 'approved' which is boolean where 1=true and 0=false. What I want to do in my view is that I only want to show the data of the user with the 0/false value. What are the steps I need to make to achieve this? I'm really new to Laravel or rather at Web Development in general.

$datas=User::where('approved','0')->get();
Now in your blade use ......
#foreach($datas as $data)
#endforeach

There are so many ways to do it. First is you can directly use where clause for it like this one.
User::where('approved', 0)->get();
Second is to use local scope. In your model you will put this one.
public function scopeApprovedUser($query) {
return $query->where('approved', 0);
}
and call it to your controller like this.
User::approveduser();

Related

How select a single row october cms

How to select a single row on october cms?
How can a simple thing be so complicated here?
I thought it would be something to help us and not to disturb something that is as simple as
SELECT * FROM `engegraph_forms_membros`
Here it's like fighting against demons without a bible, oh god why?
Why make the query difficult for newbie?
I understand you don't speak English natively but you should watch every single one of these videos.
Does the record belong to a model in a plugin? Here are the docs on how to work with models.
You make a plugin, set the database which creates models, and then make components to be ran in your CMS Pages.
In a component.php file you can have something like this: Here I am calling the model class Agreements with use Author\Plugin\Models\Agreements;. This allows me to run a function/method to retrieve all agreements or one agreements using laravel's eloquent collection services.
Lets say we have the ID of a record. Well we can either call on the Agreements model with ::find or with ::where. You will noticed I have two functions that essentially do the same thing. ::find uses the primary key of the models (in my case the id) and will return a singular record. *Note that find can take an array and return a collection of records; like ::where. Using ::where we are going to look for the ID. *Note ::where always returns a collection which is why I have included ->first().
<?php namespace Author\Plugin\Components;
use Session;
use Input;
use Crypt;
use Db;
use Redirect;
use Illuminate\Contracts\Encryption\DecryptException;
use October\Rain\Support\Collection;
use Author\Plugin\Models\Agreements;
class GetAgreement extends \Cms\Classes\ComponentBase
{
public function componentDetails()
{
return [
'name' => 'Get one agreement',
'description' => 'Get an agreement to change or delete it'
];
}
public function onRun() {
$this->page['agreement'] = $this->getWithFindAgreement;
}
public function getWithFindAgreement() {
$id = 1;
$agreement = Agreements::find($id);
return $agreement;
}
public function getWithWhereAgreement() {
$id = 1;
$agreement = Agreements::where($id)->first();
return $agreement;
}
}
If for some reason you aren't working with models, here are the docs to work with Databases. You will have to register the use Db; facade.
Here call the table you want and use ::where to query it. *Note the use of ->first() again.
$users = Db::table('users')->get();
$user = $users->where('id', 1)->first();
There are two simple ways to select a single row:
This will give you the'first' record in the selected recordset.
SELECT top 1 * FROM `engegraph_forms_membros`
This will select all the records that meet the predicate requirement that the value of <columnname> is equal to <value>
SELECT * FROM `engegraph_forms_membros` where <columnname>=<value>
If you select a record where multiple values meet that requirement, then you can (randomly) pick one by combining the solutions...
SELECT top 1 * FROM `engegraph_forms_membros` where <columnname>=<value>
But be aware that without an ORDER BY clause, the underlying data is unordered and prone to change uncontrollably, which is why most people (including your boss) will find the use of 'Top' to be improper for real use.

Eliminate data from active dataprovider in Yii2

I'm looking for a way to rotate via data in ActiveDataProvider and erase some rows. I have rather peculiar data structure and I can't get precise data I need with ->andFilterWhere
I know it is possible to use SqlDataProvider but I would prefer to get to know a way to be able to do foreach on every row in ActiveDataProvider and just unset those ones I don't need.
I'm not pasting my code - I use rather simple controller and model generated via Gii - so nothing crazy here.
Will be really glad if anyone could point me into the right direction.
You can do something like this:
$dataProvider = new ActiveDataProvider(['query' => $query]);
foreach ($dataProvider->models as $model) {
//your logic
}
ok, I have found an answer, so I thought I'd share.
To still be able to use active dataprovider and make a funky sql query I want the long way - I prepared a prequery which gave me only id's of rows I wanted and then I passed them into normal search query in ActiveDataProvider's search.
$query->andFilterWhere([
'customer_id' => $tempids,
This way what I got was - I limited the main query only to preselected rows.
You may use getModels() and setModels() to modify list of models available in data provider:
$models = $dataProvider->getModels();
foreach ($models as $index => $model) {
if (/* some condition */) {
unset($models[$index]);
}
}
$dataProvider->setModels($models);
But this is inefficient (you're creating unnecessary models) and will does not work correctly with pagination (you may get less records on page than you want, including edge case with empty page). It is better idea to filter records on query level - if you're able to filter them using SQL, you should be able to do this using ActiveQuery. It should be possible to add most conditions using andWhere(), including handling subquery:
$subquery = (new Query())->from(/* ... */)-> // ... rest of conditions
$dataProvider->query->andWhere(['customer_id' => $subquery]);

Clone data from one to another database column in Laravel

I have two columns quantity and remaining_quantity in my stock table. I wanted to copy same data from quantity to remaining_quantity while doing a create function. Is there any function in Laravel for that?
You can do that by creating an observer.
1- Create a folder called observers in you app folder.
2- Create a file named MyModelObserver.php for example StockObserver.php.
3- Prepare your class like the following:
<?php
namespace App\Observers;
class StockObserver
{
//
}
Inside that class you can create creating, created, updated, updated, deleting, deleted, saving and saved methods. Which their jobs are obvious from their names.
For more details see => https://laravel.com/docs/5.5/eloquent#events
For example the following code will do something everytime an object of Stock model is created.
<?php
namespace App\Observers;
use App\Stock;
class StockObserver
{
public function created(Stock $stock)
{
$stock->remaining_quantity = $stock->quantity;
$stock->save()
}
}
But all these code won't be effective unless you observe that in the AppServiceProvide .. so in the boot method in AppServiceProvider write the following.
\App\Stock::observe(\App\Observers\StockObserver::class);
That's it .. Hope it helps.
Yes, a few different ways to do that. An easy, dirty way would be to just have two queries,
$quantity = StockTable::find($id);
StockTable::create([
'remaining_quantity' => $quantity->quantity
]);
So you grab the record you want to copy a bit of, and then set it as the remaining quantity on your creating record.

Accessing variables outside class

I will try to explain my issue as good as I can.
I have a class with functions, the purpose of one function is to fetch information from the database and display it.
Everything works as it should, but now I need to access some variables to use them outside my class in another file, I don't know how this should be done so I'm wondering if someone can guide me.
function fetch(){
$this->_select_query = '
SELECT movies_id, movies_title, movies_director, movies_year, movies_category_id, cat.name
FROM movies
LEFT JOIN cat ON id = movies_category_id'
or die(mysqli_error());
$this->_stmt = $this->_mysqli->prepare($this->_select_query);
$this->_stmt->execute();
$this->_stmt->bind_result($this->_select_id, $this->_select_title, $this->_select_director, $this->_select_year, $this->_select_category_id, $this->_select_category_name);
$this->_stmt->store_result();
while($this->_stmt->fetch()){
echo '<tr>
<td>'.$this->_select_title.'</td>
<td>'.$this->_select_director.'</td>
<td>'.$this->_select_year.'</td>
<td>'.$this->_select_category_name.'</td>
<td>Edit</td>
<td>Delete</td>
</tr>
';
}
}//close function fetch
The function fetch is inside a class called movies, now on another page I have a form to edit(update) these movies and I would like to return the title, director etc.. inside that form so it is easy to notice what you are changing.
Now I do know how to do this using php procedural but not with object oriented php.
As you can also notice here I echo out the whole table (another part of the table is on a diffirent page)
So because of this I can't use $movies->fetch()
I do hope someone can give me some more information on my issue since I feel a bit lost at this point, and while staring too much on the same code you can become confused and mix up stuff.
Kind Regards
Edit: should I be using globals, constants ?
You should refactor your code.
As you are saying, you can't do $movies->fetch() since it echoes the table. That's a sign of braking the Single Responsibility Principle. You should divide your function into two: one function that fetches (and returns) the data, and another one that takes data as a parameter and returns a table with the data.
That way, you can reuse the first one when you want to get the values for the edit form.
Since you have a procedural background, I'd recommend that you create a new class that represents a "movie" that has the required fields. Then, for each row in your table you should create an instance of that class and populate the fields, and ultimately return all those instances.
Sorry for not posting any code at the moment, I realized that would have been easier.

Yii - using MySQL AS clause field

Let's say I want to have a provide CActiveDataProvider for a CGridView. I need to put a SUM(invitesCount) AS invites into a Provider result. How to retrieve it? I guess I cannot just use $dataProvider->invites?
You need to specify the following in your relationinvites
'invites '=>array(self::BELONGS_TO, 'CampaignFund', 'campaign_id', 'select' => 'SUM(invitesCount)'),
and use this relation in your criteria.
Several other options:
Use CStatRelation
invitesCount=>array(self::STAT,'Invites','foreign_key_field');
The addition of a public property can work. However, the field would only be set if you altered the default find query to include this new condition. This can be done by overriding defaultScope() or creating a new scope and using it whenever invitesCount is required.
Another option would be to create a database view from the required query and create a new Model from that database view.