Laravel Query Builder : Where pivot not in - sql

wherePivotIn is mentionend here (under Filtering Relationships Via Intermediate Table Columns) but I can't find anything about the opposite function.
As the wherePivotIn already exists but not the wherePivotNOTIn, I edited this file : vendor/laravel/framework/src/Illuminate/Database/Eloquant/Relations/BelongsToMany.php
And added this function
public function wherePivotNotIn($column, $values, $boolean = 'and', $not = false)
{
$this->pivotWhereIns[] = func_get_args();
return $this->whereNotIn($this->table.'.'.$column, $values, $boolean, $not);
}
Now the wherePivotNotIn exist and is working. But my question is:
Is it safe to update this file?
In case of update, I guess I will lose this...

After dinging a bit, I found out that the whereIn method accept more than 2 arguments.
We juste have to use it like that to use a "wherePivotNotIn"
->wherePivotIn($column,$value,'and','NotIn')
No need to declare a new class or using scope!

Yeah don't update vendor files that's a no no. Instead , create a class that extends BelongsToMany and put your implementation in there. You'll lose your changes as soon as the file updates.

Never edit what is inside the vendor directory. Create your own method to meet your need, in case it does not exist.
In your case, you can define a Local Query Scope
It will look like:
class Task extends Model
{
public function scopeWherePivotNotIn($query)
{
/**/
}
}
$tasks = Task::wherePivotNotIn()->get();

Related

Compare two database fields in extbase repository

I am using TYPO3 8. In my extension I have a database table "company" in which I store for each company the total number of places (number_places) and the number of occupied places (occupied_places).
Now I want to limit the search to companies which have available places left.
In MySQL it would be like this:
SELECT * FROM company WHERE number_places > occupied_places;
How can I create this query in the extbase repository?
I tried to introduce the virtual property placesLeft in my model but it did not work.
I don't want to use a raw SQL statement as mentioned below, because I already have implemented a filter which uses plenty of different constraints.
Extbase query to compare two fields in same table
You can do it like this in your repository class, please note the comments inside the code:
class CompanyRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
public function findWithAvailablePlaces(bool $returnRawQueryResult = false)
{
// Create a QueryBuilder instance
$queryBuilder = $this->objectManager->get(\TYPO3\CMS\Core\Database\ConnectionPool::class)
->getConnectionForTable('company')->createQueryBuilder();
// Create the query
$queryBuilder
->select('*')
->from('company')
->where(
// Note: this string concatenation is needed, because TYPO3's
// QueryBuilder always escapes the value in the ExpressionBuilder's
// methods (eq(), lt(), gt(), ...) and thus render it impossible to
// compare against an identifier.
$queryBuilder->quoteIdentifier('number_places')
. \TYPO3\CMS\Core\Database\Query\Expression\ExpressionBuilder::GT
. $queryBuilder->quoteIdentifier('occupied_places')
);
// Execute the query
$result = $queryBuilder->execute()->fetchAll();
// Note: this switch is not needed in fact. I just put it here, if you
// like to get the Company model objects instead of an array.
if ($returnRawQueryResult) {
$dataMapper = $this->objectManager->get(\TYPO3\CMS\Extbase\Persistence\Generic\Mapper\DataMapper::class);
return $dataMapper->map($this->objectType, $result);
}
return $result;
}
}
Notes:
If you have lots of records to deal with, I would - for performance reasons - not use the data mapping feature and work with arrays.
If you want to use the fluid pagination widget, be sure you don't and build your own pagination. Because of the way this works (extbase-internally), you'd get a huge system load overhead when the table grows. Better add the support for limited db queries to the repository method, for example:
class CompanyRepository extends \TYPO3\CMS\Extbase\Persistence\Repository
{
public function findWithAvailablePlaces(
int $limit = 10,
int $offset = 0,
bool $returnRawQueryResult = false
) {
// ...
$queryBuilder
->setMaxResults($limit)
->setFirstResult($offset);
$result = $queryBuilder->execute()->fetchAll();
// ...
}
}
I think you cant do this using the default Extbase Query methods like equals() and so on. You may use the function $query->statement() for your specific queries like this.
You also can use the QueryBuilder since TYPO3 8 which has functions to compare fields to each other:
https://docs.typo3.org/typo3cms/CoreApiReference/latest/ApiOverview/Database/QueryBuilder/Index.html#quoteidentifier-and-quoteidentifiers
It's fine to use this QueryBuilder inside Extbase repositories. After this you can use the DataMapper to map the query results to Extbase models.
In case of using "statement()" be aware of escaping every value which may cause any kind of SQL injections.
Based on the current architecture of TYPO3, the data structure is such that comparing of two tables or, mixing results from two tables ought to be done from within the controller, by injecting the two repositories. Optionally, you can construct a Domain Service that can work on the data from the two repositories from within the action itself, in the case of a routine. The service will also have to be injected.
Note:
If you have a foreign relation defined in your table configuration, the results of that foreign relation will show in your defined table repository. So, there's that too.

overriding already overridden classes with a module - Prestashop 1.6

I KNOW THIS QUESTION IS NOT SPECIFICALLY TIED TO PROGRAMMING. BUT I REALLY WANT TO UNDERSTAND PRESTASHOP'S BEHAVIOUR OF OVERRIDING FILES VIA MODULES.
I want to extend a MYSQL table, let's say, Orders. A raw sql query in Module's install method would get this, no problem. But I wanna add this column to Order Model as well, which is where the main problem would come. Since I must override it like this:
public function __construct($id = null, $id_lang = null)
{
parent::__construct($id, $id_lang);
self::$definition['fields']['new_column'] = array('type' => self::TYPE_STRING);
}
My question is, how do I make sure that if override directory already has an Order.php with a __construct, how do I make it to merge changes rather than throwing error.. Is it possible?
Prestashop doesn't encourage using of overrides within modules at all. Because how I know there is no way to merge two overrides and only the last one will work if you will find a way to install a module with the second override. So they recommend extending existing classes and add all necessary data from there. For example, in your case, it should be something like this
class Order extends OrderCore
{
public $new_filed;
public function __construct($id = null, $id_lang = null)
{
Order::$definition['fields']['new_column'] = array('type' => self::TYPE_STRING);
parent::__construct($id, $id_lang);
}
}
and just include this class file inside your module. So if something similar will be included within another module no conflict should appear except if the properties will have the same name.

executing a sql code for creating a table and database in zend framework

I wrote a sql script and in it I created a table ;
Now I need to know ,how I can execute this script? (with which codes?)
And I have another question : where? where I must write this codes?(which folder in zend project?)
if it is possible for you please explain with an example.thanks
Creating tables in the database
Zend Framework is not supposed to be the one creating the tables, thus, my suggestion is to run those scripts in other environment.
The fastest one is, probably, the very own SQL shell, but you can use another software such as MySQLWorkbench if you are using MySQL.
Once the tables are created, the access to the tables is made this way:
Introduction
When you are using Zend Framework, you are making use of the MVC pattern. I suggest you to read what is that: Wikipedia MVC
If you read the Wikipedia link, you probably know now that the acess to the database is going to be made by the model.
Thus, if you followed the recommended project structure that Zend provides you will have a models folder under your application folder. There, you are supposed to implement the classes that will make access to the DB.
But well... you now know where to locate those classes but you will ask me: how? It's easy if you know where to search. ZF provides an abstract class called Zend_Db_Table_Abstract that has all the methods that will make your life easier talking about interaction with your database's tables. This is the class that your classes should implement.
Example
Let's suppose you've got a page in your website in which you want to show to the user a list of products of your local store. You have a table in your database called "products" in which you have all the useful information such us name, price and availability.
You will have a controller with an action called indexAction() or listAction() this action is prepared to send the data to your view and will look like:
class Store_ProductsController extends Zend_Controller_Action {
public function indexAction(){
//TODO: Get data from the DataBase into $products variable
$this->view->products = $products;
}
}
And your view file will that that products variable and do sutff with it.
But now comes the magic, you will have a class that will access to the database as I've said, it'll be like:
class Model_Store_Products extends Zend_Db_Table_Abstract{
protected $_name = 'products';
public function getAllProducts(){
$select = $this->$select()
->from(array('P'=>$this->_name),
array('id', 'name', 'price', availability));
$productsArray = $this->fetchAll($select);
return $productsArray;
}
}
And ta-da, you have your array of products ready to be used by the controller:
class Store_ProductsController extends Zend_Controller_Action {
public function indexAction(){
$model = new Model_Store_Products();
$products = $model->getAllProducts();
$this->view->products = $products;
}
}
It can be said that, since fetchAll is public function, and our select does basically nothing but set which columns do we want (it doesn't even have a where clause), in this case, it would be easier to call the fetchAll directly from the controller with no where and it will recover the whole table (all columns):
class Store_ProductsController extends Zend_Controller_Action {
public function indexAction(){
$model = new Model_Store_Products();
$products = $model->fetchAll();
$this->view->products = $products;
}
}
Thus, our function in the model is not even needed.
This is the basic information of how to access to the database using Zend Framework. Further information of how to create the Zend_Db_Table_Select object can be found here.
I hope this helps.

Check if property exists in RavenDB

I want to add property to existing document (using clues form http://ravendb.net/docs/client-api/partial-document-updates). But before adding want to check if that property already exists in my database.
Is any "special,proper ravendB way" to achieve that?
Or just load document and check if this property is null or not?
You can do this using a set based database update. You carry it out using JavaScript, which fortunately is similar enough to C# to make it a pretty painless process for anybody. Here's an example of an update I just ran.
Note: You have to be very careful doing this because errors in your script may have undesired results. For example, in my code CustomId contains something like '1234-1'. In my first iteration of writing the script, I had:
product.Order = parseInt(product.CustomId.split('-'));
Notice I forgot the indexer after split. The result? An error, right? Nope. Order had the value of 12341! It is supposed to be 1. So be careful and be sure to test it thoroughly.
Example:
Job has a Products property (a collection) and I'm adding the new Order property to existing Products.
ravenSession.Advanced.DocumentStore.DatabaseCommands.UpdateByIndex(
"Raven/DocumentsByEntityName",
new IndexQuery { Query = "Tag:Jobs" },
new ScriptedPatchRequest { Script =
#"
this.Products.Map(function(product) {
if(product.Order == undefined)
{
product.Order = parseInt(product.CustomId.split('-')[1]);
}
return product;
});"
}
);
I referenced these pages to build it:
set based ops
partial document updates (in particular the Map section)

creating base model class in yii

In my application, i have fields that are common to all tables, like create date, update date etc. To assign these values i'm using beforeValidate callback. Now, this callback is same for all models.
To avoid code duplication, i want to create a base model class.
But, when I tried to create a base model, yii thrown error saying table cannot be found in database, which is true since I dont have any table for this base model.
Is there any way I can create a base model class.
Yes, if you work with dynamic DB structure or have other reasons to work with Yii ActiveRecord without creating classes for each table in DB, you may use smartActiveRecord yii extension
I separated it few minuts ago from my other extension -- AR behavior that adds versioning to any model (it copies all data on insert & update to special table (and create it if it's absent), that have a same structure as source table + "revision field" and primary key extended by this field.
Look at SmartAR.php source, there is example of usage in comments.
Take a look at CTimeStampBehavior.
Incase that doesn't help you, you can just write a behavior class yourself.
Hope this helps.
Edit:Assuming you are using ActiveRecords.
If you want to create a new base model, you can do this:
abstract class MyBaseARClass extends CActiveRecord{
protected function beforeValidate(){
if(parent::beforeValidate()){
// assign your fields
return true;
}
else return false;
}
}
Have you created a base table? Thinking about the Yii framework it may be easier to have a relationship between a model and the base model.
In your case, you need to override
public static function model($className=__CLASS__)
{
return parent::model($className);
}
in every child class so Yii would know which table to use for your model. Otherwise it will try and use base class as table name.
I.e.
class User extends BaseActiveRecord {
public static function model($className=__CLASS__)
{
return parent::model($className);
}
}