Why is my find clause not working? - mysql

I have three models: Company, Office, CompanyPersonTask. The Company model has many Office and has many CompanyPersonTask.
So, why is this code:
public function getCompaniesByRegion($region){
$options['conditions'] = array("UPPER(Office.region) LIKE UPPER('".$region."%')");
return $this->find('all', $options);
}
resulting in the following error ?
"Unknown column 'Office.region' in 'where clause'"
The region column is present in the offices table.

As if you have specified the proper association-ship between Company with Office and CompanyPersonTask. i.e. Company hasMany Office and Company hasMany CompanyPersonTask.
Then you could write it as:
In your Company Model write:
public $actAs = array('Containable');
Your method should be:
class AppController extends Controller
{
public $uses = array('Company', 'Office', 'CompanyPersonTask');
protected function _getCompaniesByRegion($region){
return $this->Company->find('all', array('contain' =>
array('Office' => array('conditions' => array("UPPER(Office.region) LIKE " => "UPPER('".$region."%')")))
)
);
}
}
You can call this method into any controller using $this->_getCompaniesByRegion($region_val);

Related

Laravel: hasMany relationship + where condition fails

I have a Customer Eloquent model. Customer can have multiple WishLists where he / she can add some products. Typical ecommerce functionality.
The point is that Customer can belong to many Users models.
This was easy:
public function users()
{
return $this->belongsToMany(User::class, 'users_sync_customers', 'customer_uuid', 'user_id')
->withTimestamps()
->orderBy('last_name', 'asc');
}
So I can get all Customers assigned for logged in user by
auth()->user()->customers 🎉
As I mentioned, Customer can have multiple Wishlists:
public function wishLists()
{
return $this
->hasMany(WishList::class, 'customer_uuid', 'uuid')
->where('user_id', '=', auth()->user()->id); // <----- this will fail when I log out
}
but WishList is scoped to both Customer UUID and User ID.
Above relationship works but only when I'm logged in obviously.
As soon as I log out the auth()->user()->is is NULL and I get:
ErrorException {#1483 #message: "Trying to get property 'id' of
non-object"
Question: How can I reference in wishLists() the user_id value?
WishList model has this:
public function user()
{
return $this->belongsTo(User::class, 'user_id', 'id');
}
So can I use something like $this->user->id?
edit:
Nope, this also doesn't work.
you must check that the user is logged in?
Auth::check() ? Auth::user()->id : null

Yii2 Restful. How can i receive data from 3 tables

I want to receive data like this:
categories
----category1
----category2
topProducts
----product1
--------photo1
--------photo2
----product2
--------photo1
--------photo2
I need get all categories and top x products.
Each product has two photos.
How can i do this by using yii2 restful?
Thanks.
the query shold look something like this
Category::find()
->with(['subcategories','topProducts', 'topProducts.images'])
->all();
you can use joinWith if you absolutely want a single query
if you retrieve your data with an ActiveController, you need to specify extraFields to the Category model. (here's a rest-specific usage example - rest of the guide should prove usefull as well)
Category model:
public function extraFields() {
return ['subcategories', 'topProducts'];
}
// product relation
public function getTopProducts(){
return $this->hasMany(Product::className(), ['category_id' => 'id'])
// ->order()->where() // your criterias
->limit(10);
}
// subcategories
public function getChildren(){
return $this->hasMany(Category::className(), ['id' => 'parent_id']);
}
Product model:
public function extraFields() {
return ['iamges'];
}
public function getImages(){
return $this->hasMany(Image::className(), ['product_id' => 'id'])
}
ps. since you haven't posed any code or table structure, all relations in my example are based on standard naiming convention

Join multiple tables Eloquent

Laravel version 4.2
I am trying to Join multiple tables and get results
I have now 2 tables
1- projects_info (id - pro_title - pro_address ...)
2- projects_images (id - image - image_id)
I need to grape the related images from the 'projects_images' where image_id = projects_info id
here what I try
here is my Route
//Projects Route
Route::get('our-projects', 'projectController#currentProjects');
Route::get('project/{id}', 'projectController#viewProject');
//Projects details
//Route::get('project/{id}/about-project', 'projectController#viewProject');
Route::get('project/{id}/about-project', array('as' => 'about-project', 'uses' => 'projectController#viewProject'));
Route::get('project/{id}/project-images', array('as' => 'project-images', 'uses' => 'projectController#viewProjectImages'));
Projects Model
class Projects extends Eloquent implements UserInterface, RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'project_info_arabic';
public function projectImages()
{
return $this->belongsTo('ProjectsImages', 'image_id');
}
}
ProjectsImages Model
class ProjectsImages extends Eloquent implements UserInterface, RemindableInterface
{
use UserTrait, RemindableTrait;
protected $table = 'projects_images';
public function project()
{
return $this->hasOne('Projects', 'id');
}
}
and this is my ProjectController
public function currentProjects()
{
$pro = Projects::all();
return View::make('projects.currentProjects', ['pro' => $pro]);
}
public function viewProject($id)
{
$vp = Projects::find($id);
return View::make('projects.viewProject', ['viewPro' => $vp]);
}
public function viewProjectImages($id)
{
$vpi = ProjectsImages::with('project')->get();
//$vpi = DB::table('projects_images')->select('id', 'image', 'image_id')->get();
return View::make('projects.projectDetails.projectImages', ['viewProImg' => $vpi]);
}
and here is how I am trying to include each page in my projectsDetails VIEW
<div class="mCustomScrollbar">
#if(Request::path()=="project/$viewPro->id/about-project")
#include('projects.projectDetails.aboutProject')
#elseif(Request::path()=="project/$viewPro->id")
#include('projects.projectDetails.aboutProject')
#elseif(Request::path()=="project/$viewPro->id/project-images")
#include('projects.projectDetails.projectImages')
#endif
</div>
and last the projectImages VIEW
<ul>
#foreach($viewProImg as $vpi)
<li class="col-sm-3 col-xs-12">
{{ HTML::image("images/projects/$vpi->image", '', array('class'=>'img-responsive')) }}
</li>
#endforeach
</ul>
My Problem
1- what I got here is all the images in the table it should be only the images related to this project
any help here please
First of all, the project has many images
public function projectImages()
{
return $this->hasMany('App\ProjectsImage');
}
.. and the image belongs to a project
public function project()
{
return $this->belongsTo('App\Project', 'project_id');
}
You should always refer to the model. If you are referring to a model then you should have in mind that its good practice to name the models in singular form, as in Project and ProjectImage. In Laravel, they expect you to have name the tables name in plural and the model name in singular. So if you haven't explicit set the table name, it will look for the model name plus a s (ProjectS).
Then, you can call the projectImages -function from a Project object. So in the view it will look something like this
#foreach($project->projectImages()->get() as $image)
// Do what you want with each project images
#endforeach

empty response on model using union

I have the following code
public function findAccessible(Query $query, array $options){
return $this->findPublic($query, $options)
->union($this->findMyAdmin($query, $options));
}
public function findPublic(Query $query, array $options){
return $query
->where(['public' => true]);
}
public function findMyAdmin(Query $query, array $options){
return $query
->where(['admin_user_id' => $options['User.id']]);
}
The findAccessible call gives me this error message in Chrome: ERR_EMPTY_RESPONSE
No other error message, no entry in error log. I am sure that is because of the union call. How to do it?
What I want to achieve:
groups hasAndBelongsTo users
groups: id, name, admin_user_id, public
I would like to get groups
1) what are public groups (This is ok, findPublic method)
2) where admin_user is the given user (This is ok, findMyAdmin method)
3) in where the given user is a member (This is ok, I could do it with an other find()->matching call)
4) which are accessible for the user, eg. public OR the given user is admin OR a member - meaning the union of 1), 2) and 3) - that is with what I am struggling. If I put all these to one find method I can not define OR relationship for the membership, as that is done by matching what is translated into an inner join.
I found a really ugly but working solution.
public function findAccessible(Query $query, array $options){
$qq = $this->query($query);
$memberships = $qq->matching('Users', function($q) use ($options){
return $q->where(['Users.id' => $options['User.id']]);
});
foreach($memberships as $m){
$memberInGroup[] = $m->id;
}
return $query
->where(['public' => true])
->orWhere(['admin_user_id' => $options['User.id']])
->orWhere(['Groups.id IN' => $memberInGroup]);
}
I hope somebody will find a better solution and post here.

Fetching from 2 or more related tables value in Zend Framework

i'm new to Zend Framework (and new to this forum too :D ) and i find this tricky problem about if you want to fetch from 3 related tables. let's say, if i have these sql query:
SELECT p.painting_id, p.painting_title
,p.painting_filename,a.artist_name,c.pc_name FROM painting p, artist
a, painting_category c WHERE a.artist_id=p.artist_id AND
c.pc_id=p.pc_id;
and i want to do this too:
SELECT p.painting_id, p.painting_title
,p.painting_filename,a.artist_name,c.pc_name FROM painting p, artist
a, painting_category c WHERE a.artist_id=p.artist_id AND
c.pc_id=p.pc_id AND p.painting_id= $p_id;
the case is, first, i want to display all paintings (with artist name and category), then, when the user click the painting, it will go to another page and display that painting only (with artist name and category also).
i have made this progress in models:
class Application_Model_DbTable_Painting extends Zend_Db_Table_Abstract
{
protected $_name = 'painting';
protected $_referenceMap = array(
'Artist' => array(
'columns' => array('artist_id'),
'refTableClass' => 'Artist',
'refColumns' => 'artist_id'
),
'PaintingCategory' =>array(
'columns' => array('pc_id'),
'refTableClass' => 'PaintingCategory',
'refColumns' => 'pc_id'
)
);
class Application_Model_DbTable_Artist extends Zend_Db_Table_Abstract
{
protected $_name = 'artist';
protected $_dependentTables = 'Model_DbTable_Painting';
}
s
class Application_Model_DbTable_PaintingCategory extends Zend_Db_Table_Abstract
{
protected $_name = 'painting_category';
protected $_dependentTables = 'Model_DbTable_Painting';
}
What kind of function should i add in the model and what should i write in the controller and view script to get result like the SQL query i wrote above ? tell me if i've made mistake.
i will really appreciate if you would give me some example related to my problem. thanks
This is a similar question and it might help you:
Zend Framework join
Apart from it you can also write and execute SQL statements directly in Zend Framework.