How to get data of 2nd table yii find all criteria join - php

This is companycontent model relations:
public function relations() {
return array(
'company_content_lang' => array(self::HAS_MANY, 'CompanyContentLang', 'company_content_id'),
);
}
This is my query:
$criteria = new CDbCriteria();
$criteria->select='t.tab_content, mv.label AS label, t.is_active';
$criteria ->join='INNER JOIN master_value as mv
on mv.value = t.tab_type
AND value_code = "tab_content"
AND locale = "' . Yii::app()->language . '"';
$criteria ->condition = 'company_id = :company_id AND is_deleted =0';
$criteria ->params=array(':company_id' => (int) $id);
$criteria->order='mv.order';
$modelContent = CompanyContent::model()->findAll($criteria);
Relationship between company_content and master_value is company_content.tab_type = master_value.value AND master_value.value_code='tab_content'. So I can't make this relation in company_content model.
Please show me how to get "mv.label AS label" value.

First, show us the relations() at CompanyContent model.
Usually, it's just a simple thing. Just add public property/variable inside the CompanyContent, ex:
class CompanyContent extends CActiveRecord
{
public $label; //added
...

Related

laravel and pivot table

I have 3 tables
Game(id, name), GameCategory(game_id, category_id), Category(id, title).
Partial code of classes:
class Game extends \Illuminate\Database\Eloquent\Model
{
protected $fillable = [
'name',
'title'
];
public function categories()
{
return $this->hasMany('VanguardLTE\GameCategory', 'game_id');
}
}
class Category extends \Illuminate\Database\Eloquent\Model {
protected $fillable = [
'title'
];
public function games()
{
return $this->hasMany('VanguardLTE\GameCategory', 'category_id');
}
}
class GameCategory extends \Illuminate\Database\Eloquent\Model {
protected $fillable = [
'game_id',
'category_id'
];
public function category()
{
return $this->belongsTo('VanguardLTE\Category');
}
public function game()
{
return $this->belongsTo('VanguardLTE\Game');
}
}
I need to select category titles for selected $game
This code give me only category_id.
$g_categories = $game->categories->pluck('category_id')->toArray();
This code not working:
$g_categories = $game->categories->category->pluck('title')->toArray();
As You mentioned to do
$g_categories = $game->categories->pluck('category_id')->toArray();
error_log('game_id'.$game->id.' category_ids:'.implode(",", $g_categories));
$g_titles = $game->categories->pluck('title')->toArray();
error_log('game_id'.$game->id.' category_titles:'.implode(",", $g_titles));
This will result with log like this:
game_id1907 category_ids:39,48
game_id1907 category_titles:,
From database side we see that data(title) is filled:
select g.id, g.name, g.title, c.id, c.title
from w_games g
join w_game_categories gc ON gc.game_id = g.id
join w_categories c ON c.id = gc.category_id
where g.id = 1907;
id
name
title
id
title
1907
OceanRulerSW
Ocean Ruler
39
Skywind
1907
OceanRulerSW
Ocean Ruler
48
Fish
Title in game is not necessary in this case but I added it here because have the same column name like title in categories.
You are accessing undefined relation .It should be
$g_categories = $game->categories->pluck('title')->toArray();
This line of code is incorrect and should be as follow:
$g_categories = $game->categories()->pluck('title')->toArray();
you did not add parentheses for categories.
The best solution is to use laravel way:
public function categories()
{
return $this->belongsToMany('VanguardLTE\Category');
}
public function games()
{
return $this->belongsToMany('VanguardLTE\Game');
}
In this way you should name your table as
category_game
and no need to define model for the intermediate table and you can simply access it through
$game->categories->pluck('title')->toArray();
in case you have any data in the pivot table just add ->withPivot('column_name') to your relationship
Refer to Laravel documentation for details

laravel eloquent - can't eager load polymorphic relation with query 'select'

I'm running Laravel 5.4 and for some reason I cannot do a column select on a 1-to-many polymorphic relation. I want to limit the columns returned in the related table.
Here's my '1 side' of my 1-to-many relationship:
class MapNodes extends Model {
protected $table = 'map_nodes';
protected $fillable = ['title'];
protected $validations = ['title' => 'max:200|string' ];
public function SystemConstants() {
return $this->morphMany('App\Modules\Models\SystemConstants', 'imageable');
}
}
Here's my 'many side' table in the relationship:
class SystemConstants extend Model {
protected $table = 'system_constants';
protected $fillable = ['name','imageable_id','imageable_type'];
protected $validations = ['name' => 'max:200|string',
'imageable_id' => 'integer|required',
'imageable_type' => 'max:45|string'];
// define this model as polymorphic
public function imageable() {
return $this->morphTo();
}
}
Here's two ways I'm trying to call it. One gets all the columns on SystemConstants, and the second I just want two columns:
$temp = MapNodes::with('SystemConstants')->find(25786);
$temp = MapNodes::with([ 'SystemConstants' =>
function( $query ) {
return $query->select('system_constants.id', 'system_constants.name' );
} ])->find(25786);
Why does the first call return the related records, but not the second? The below SQL statements for both calls look exactly the same (with the exception that I'm only wanting two columns in the second call).
select * from `system_constants` where
`system_constants`.`imageable_id` in (?) and
`system_constants`.`imageable_type` = ? - a:2:{i:0;i:25786;i:1;s:5:"Nodes";}
select `system_constants`.`id`, `system_constants`.`name` from `system_constants` where
`system_constants`.`imageable_id` in (?) and
`system_constants`.`imageable_type` = ? - a:2:{i:0;i:25786;i:1;s:5:"Nodes";}
In order to work you must add both the foreign key and primary key on the select statement:
$temp = MapNodes::with([ 'SystemConstants' =>
function( $query ) {
return $query->select('system_constants.id', 'system_constants.name', 'system_constants.imageable_id');
} ])->find(25786);

cakePHP find("list") returns empty array

I am trying to make a drop down list of users by using the foreign key [UserID].
In the controller, I have find("list"). When I debug $this->Order->SalesAgent in the controller, it prints the User Object. However, in the view page, when I debug
the result of $this->Order->SalesAgent->find("list"), shows and empty array.
Heres the Controller:
public function edit_sales_agent ($id=null) {
debug($this->Order->SalesAgent);
$this->set("users",$this->Order->SalesAgent->find("list"));
debug($this->users);
}
and heres the View:
debug($users);
echo $this->Form->create("Order");
echo $this->Form->input("UserID");
$users is the result of find("list")
Could anyone help me out?
Thanks!
Association:
class Order extends AppModel{
public $useTable = 'CustomerOrder';
public $primaryKey = 'OrderID';
**public $belongsTo = array(
"SalesAgent"=>array(
"className"=>"User",
"foreignKey"=>"UserID"**
),
Sales Agent Model:
<?php
class User extends AppModel{
public $useTable = 'UserAccount';
public $primaryKey = 'UserID';
public $order = array(
"User.LastName"=>"asc",
"User.FirstName"=>"asc"
);
public function __construct($id = false, $table = null, $ds = null) {
parent::__construct($id, $table, $ds);
$this->virtualFields['full_name'] = sprintf("(%s.FirstName+' '+%s.LastName)", $this->alias, $this->alias);
}
public function login($data){
return $this->find("first",array("conditions"=>$data['User']));
}
}
UPDATE:
Alright, so I figured out what the problem is but I dont know how to fix it.
When I type find(list), this is the query it runs:
SELECT [SalesAgent].[UserID] AS [SalesAgent__0],
[SalesAgent].[UserID] AS [SalesAgent__1] FROM [UserAccount] AS
[SalesAgent] WHERE 1 = 1 ORDER BY [User].[LastName] asc,
[User].[FirstName] asc
THis is the error it proposes:
SQL Error: The column prefix 'User' does not match with a table name
or alias name used in the query. [APP/Model/Datasource/Mssql.php, line
749]
The SalesAgent uses class User, which uses table UserAccount
I figured it out.
The problem was the query would run:
SELECT [SalesAgent].[UserID] AS [SalesAgent__0], [SalesAgent].[UserID]
AS [SalesAgent__1] FROM [UserAccount] AS [SalesAgent] WHERE 1 = 1
ORDER BY [User].[LastName] asc, [User].[FirstName] asc
where it would order by [User].LastName and [User].[FirstName].
User doesnt match the table name OR alias name, so I had to specify the order in cake.
array(
"fields"=>array("SalesAgent.username"),
' "order"=>["SalesAgent.UserID ASC"]
)
First try to configure your model association.
What is belong to what and the by running this
public function edit_sales_agent ($id=null) {
$users = $this->Order->SalesAgent->find("list");
$this->set("users",$users);
}
view try this
echo $this->Form->input("user_id");
You should have list of users.

Yii framework: get sum by scope

I have scopes in my User model:
public function scopes()
{
return array(
'sumPrice'=>array(
'select'=>'SUM(`price`)',
),
);
}
And I want get sumPrice in controller, but I dont know what is a way to do this. I tried:
$sumPrice=User::model()->sumPrice(); //it returns empty record (user model filled by NULLs)
$sumPrice=User::model()->sumPrice()->count(); //it returns count records in user
$sumPrice=User::model()->sumPrice()->findAll(); //it returns all records in user
But there isn't function which return sum, so how to get it?
Solved:
$sumPrice = Yii::app()->db->createCommand('SELECT SUM(`price`) AS `sum` FROM `user`')->queryAll();
var_dump($sumPrice[0]['sum']);
You need a Statistical query on your active record, define a relation on your model
class Post extends CActiveRecord
{
public function relations()
{
return array(
'commentCount'=>array(self::STAT, 'Comment', 'post_id'),
'categoryCount'=>array(
self::STAT, 'Category', 'post_category(post_id, category_id)'
),
);
}
}
Yiiframework
you can use ActiveRecord :
$criteria = new CDbCriteria;
$criteria->select='SUM(your_column) as sum';
$criteria->condition='your_condition';
$user = User::model()->find($criteria);
and you need to declare: public $sum; in your model class. (Using the above example.)

Search with a joined table using YII

I have the following table structure.
tb_posts has the field author_id which relates to tb_author.id
in YII i have the following in my posts activeRecord
public function relations()
{
return array(
'authorRelation' => array(self::BELONGS_TO, 'authorRecord', 'author')
);
}
How i do a search of posts of an authors with name 'foo'? I am trying the following with no success
$criteria=new CDbCriteria;
$criteria->with = array('authorRelation');
$criteria->together = true;
$criteria->compare( 'author.name', 'foo', true );
$posts=PostsRecord::model()->findAll($criteria);
Set table alias for your models at init.
class PostsRecord extends CActiveRecord
{
// ...
public function init() { $this->setTableAlias( 'postsrecord' ); }
// ...
}
class AuthorRecord extends CActiveRecord
{
// ...
public function init() { $this->setTableAlias( 'authorrecord' ); }
// ...
}
Finally:
$condition=new CDbCriteria;
$condition->with = array('authorRelation');
$condition->together = true;
$condition->condition = 'authorrecord.name=:authorname';
$condition->params = array( ':authorname' => 'foo' );
$posts=PostsRecord::model()->findAll($condition);
Your relation should be 'authorRelation' => array(self::BELONGS_TO, 'authorRecord', author_id'). The 3rd parameter is the foreign key.
The second part of the code doesn't have any errors, the search should work if you set up the relations correctly.

Categories