Build columns while running a query in yii2 - yii2

Create columns while running query in yii2
in controller :
query :
$query=Reports::find()->select(['report As type','title','imageFile','id','body'])->where(['like', 'title',''.$test.'' ])->orderby('id desc');
i would build column type but Does not work.

for see the result of alias you should add in your Reports model a public var with the same name for get the value
class Reports extends \yii\db\ActiveRecord
{
public $type;
.....
then you can access to the value as
$myModels->type

Related

Laravel model referencing wrong table in query

I am sure this is because of the eloquent, but the query is using the wrong table in SELECT.
here my model:
class Subcategory extends Model
{
public function subcategory()
{
return $this->belongsTo(Category::class);
}
}
and here is my Controller:
class SubcategoriesController extends Controller
{
public function index()
{
$subcategories = Subcategory::all();
return view('pages.subcategories', compact('subcategories'));
}
}
and finally here my error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'developmnet.site.subcategories' doesn't exist (SQL: select * from `subcategories` where `category_slug` = budgets limit 1)
as you can see from the error the table referenced in the query is subcategories when it should be categories table.
My question is how to reference the correct table in this model as I already have one for my main categories and it is working just fine.
To overwrite the table name of a model you can define the protected $table property. In Your case:
class Subcategory extends Model
{
protected $table = 'categories';
// ..
}
If you don't do that, Laravel will derive the table name from the class name. In your case: Subcategory => subcategories.

Table name having additional underscores added

I have an API that grabs data from a table, serialises the data and then sends back via the service. The code is written using CakePHP using MySQL.
When I pass in the table name (such as RX_Scaled), an error is being returned that the table r_x_scaled can't be found (which don't surprise me, the table name in the database is rx_scaled).
My Model/Table for rx_scaled is defined like this
class rx_scaleds extends Table
{
public function initialize(array $config)
{
parent::initialize($config);
$this->table('rx_scaled');
}
With the Model/Entity
class rx_scaled extends Entity
{
}
My service API is set like this within the APIController.php file
public function getData($tablename, $id="", $filter = "-", $order = "-", $take = 0)
{
$the_table = $tablename;
$this->autoRender = false;
$table = TableRegistry::get($tablename);
$data = null;
switch (strtolower($the_table))
{
case "rx_scaled":
$data = $table->find();
echo $data;
break;
}
(this is truncated)
The odd thing is that this error does not occur in all tables.
I'm obviously not doing something correctly, but I'm not sure what
You named your table object rx_scaleds but then you pass RX_Scaled to the getData action
cake try not finding a Table Object named RX_Scaled try to inflect the name of the mysql table: so using cake's conventions RX_Scaled is mapped to r_x_scaled
So what can you do?
Use cake conventions
Name you table RxScaledsTable
class RxScaledsTable extends Table
Name you entity RxScaled
class RxScaled extends Entity
and pass the string 'RxScaled' to your action

Select query in hibernate annotations in spring mvc

Hi i am writing an spring mvc, employee application using mysql database,hibernate annotations and jsp . The database contains one table "Empdata" where empid is primary key.And there is a column "team" in "Empdata".I want to select employees in a specific team, example all the details of employees in "Team1".Here i can perform delete and edit operations in the application. For delete opertaion i am using
sessionfactory.getCurrentSession().createQuery("DELETE FROM Resource WHERE empid=" +resource.getEmpId()).executeUpdate();
query.I know the commandline query for select is
SELECT * FROM EmpData ERE EMPLTEAM ="Team1"
I want to know how to convert this query into hibernate.
please help,thanks in advance..
you can convert the query in the following way:
String sql = "select ed from EmpData ed where emplTeam = :emplTeam";
Query query = session.createQuery(sql);
query.setParameter("emplTeam ", team);
List<EmpData> empDataList = (List<EmpData>)query.list();
but you should have a class called EmpData containing a property emplTeam similar to the following:
#Entity
#Table(name = "EmpData")
class EmpData {
....
#Column(name = "EMPLTEAM")
private String emplTeam;
public String getEmplTeam() {
return emplTeam;
}
public void setEmplTeam(String emplTeam) {
this.emplTeam = emplTeam;
}
}
(I used annotations hibernate .. but you can do it the same way using .hbm.xml files)
For example
Query query = session.createQuery("from Student where name=:name");
query.setParameter("name", "Raj");
In your case i guess the Entity name is Empdata(The object that represent the table)
And the field in the object is team(That has getter and setter in object)
Query query = session.createQuery("from Empdata where team=:teamParam");
query.setParameter("teamParam", "team1");

Add WHERE condition to all SQL requests in Laravel

I'm creating an online tool for companies that each have a set of users in Laravel.
When a user is connected, he has a $connected_company_id variable
For every SELECT request (called by ::all(), find(), ...), i would like to add the condition: where company_id = $connected_company_id. I have found this post: laravel set an automatic where clause, but it doesn't work by overriding newQuery().
For every INSERT request, i would like to add the company_id.
Is this possible without changing my code inside all the controllers ?
I thought about extending Eloquent with customEloquent, and then make my models extend customEloquent, but I don't know how to write the code for customEloquent and if it could work.
Well, you could make use of the Eloquent Model Events. I assume you have the connected_company_id stored in the Session company_id
class BaseModel extends Eloquent{
public static function boot(){
parent::boot();
//Column to inject when inserting
static::creating(function ($obj){
$obj->company_id = Session::get('company_id');
});
//Column to inject when updating
static::updating(function ($obj){
$obj->company_id = Session::get('company_id');
});
}
}
You can extend the BaseModel class on all the models that you want the company_id to be inserted or updated. Take a look at Eloquent Model Events for more information.
The above code will automatically insert or update the company_id to the model that you extend the BaseModel to. When you do a Model::all() or Model::get(), you automatically get the company_id on that Model and you can also perform searches as you requested on Point `
Hope this helps.
well, you can just add the company id to the find query.
Model::where("company_id","=",$company_id):
Or you can create a scope:
class theModel extends Eloquent {
static $company_id;
static for_company($company_id){
self::company_id=$company_id;
return __CLASS__;
}
public function scopeCompany($query)
{
return $query->where('company_id', '=', self::company_id);
}
}
//And later
$scope=theModel::for_company($company_id);
$res=$scope::company->where(...);
Disclaimer: I haven't tried this. Just a solution I constructed. Let me know if this works. This will not work under PHP 5.3

Zend_Db_Table Base table or view not found

I have taken over an application written with the use of the Zend MVC and Zend_Db_Table for DB access. I am trying to add a new table but get the error:
Base table or view not found: 1146 Table 'maa_agencies.contact' doesn't exist
However maa_agcencies.contact very much DOES exists and is in the same DB as the rest of the tables being accessed.
Here are my steps and code:
Step 1:
Create the Model Class
file: application/models/DbTable/Contact.php
class Model_DbTable_Contact extends Zend_Db_Table_Abstract
{
protected $_name = 'contact';
}
Step 2:
Instantiate the Class the same way it's done a dozen time in a controller (all other tables work)
file: application/modules/agency/controllers/IndexController.php (also step 3)
$agency_contact = new Model_DbTable_Contact();
Step 3:
Write my data to my new table ($store_contact is an assoc array with key = column name value = value)
$agency_contact->insert($store_contact);
Is there some caching function in Zend I am unaware of?
Some special thing I need to do to tell it I added a new table?
All documentation I have come across says this is all that is required, and as I state above the file I am trying to access my table through is already accessing 2 other tables in the same DB, in fact the line just above where I instantiate my Contact model is this statement that works fine:
$sm = new Model_DbTable_SentEmail();
The name space idea seems awesome! If this system wasn't some bastardization of the framework. Here is a currently working Model
/**
* #category Model_DbTable
* #package Model_DbTable_States
class Model_DbTable_States extends Zend_Db_Table_Abstract
{
protected $_name = 'state_list';
}
Is there some vodoo in the commenting perhaps, I am unable to find anywhere in the code where a namespace is registered at all.
Change your Class names of Model Directory. Add Prefix Application_
Example: Application_Model_DbTable_Contact
You forgot to add the namespace to your class
class Yournamespace_Model_DbTable_Contact extends Zend_Db_Table_Abstract
{
protected $_name = 'contact';
}
IN your application.ini ad this line
autoloaderNamespaces[] = "Yournamespace_"