Laravel 5 joining multiple tables - sql

I am having real problems joining tables in Laravel.
I can join 2 tables but as soon as I try to join a third, i get no data
class Main extends Model
{
protected $table = 'main';
protected $primaryKey = 'id';
public function test()
{
return $this->hasOne('App\Models\Test', 'id', 'id');
}
public function row()
{
return $this->hasOne('App\Models\Row', 'id', 'id');
}
}
class Test extends Model
{
protected $table = 'test';
protected $primaryKey = 'id';
public function main()
{
return $this->belongsTo('App\Models\Main', 'id', 'id');
}
public function rows()
{
return $this->hasMany('App\Models\Row', 'id', 'id');
}
}
class Row extends Model
{
protected $table = 'row';
protected $primaryKey = 'id';
public function main()
{
return $this->belongsTo('App\Models\Main', 'id', 'id');
}
public function rows()
{
return $this->belongsTo('App\Models\Test', 'id', 'id');
}
}
I've added this to my Main model to run a query. This will output the 2 tables
public function scopeGetPart($query, somefield)
{
return $query->with('test.main')
->where('somefield', somefield);
}
This works when i run it through phpMyAdmin. I want to write this the Laravel way
SELECT * FROM
main
INNER JOIN test ON
main.id = test.id
INNER JOIN row ON
main.id = row.id
AND main.my_field = row.my_field
WHERE somefield = 103288

Without running your code, have you tried $main->with('test.rows')? This should fetch the tests of a main instance with the rows of the test.

I gave up with Eloquent as it was causing problems and used this instead which works how i wanted
DB::table('main')
->join('test', 'main.id', '=', 'test.id')
->join('row', function ($join) {
$join->on('main.id', '=', 'row.id')
->whereRaw('main.my_field= row.my_field');
})
->where('somefield', '103288');

Related

How to solve an interesting eloquent query with 3 models?

A User can join any number of INNER CIRCLES ( something like groups ). Now whenever a User list a property , I need to send emails to all the members of all the circles he has joined. What will be the query ?
Model User
public function circlemember()
{
return $this->hasMany(InnerCircleMember::class, 'member_id', 'id');
}
Model InnerCirclemember
public function member(){
return $this->belongsTo(User::class,'member_id');
}
public function circle(){
return $this->belongsTo(InnerCircle::class,'circle_id');
}
Model InnerCircle
public function circlemember()
{
return $this->hasMany(InnerCircleMember::class, 'circle_id', 'id');
}
Controller:
$allusers = User::where('status' , 1)
->whereRoleIs('broker')
->where('email_verified_at', '<>', NULL)
->where('mailforcircles', 1)
->get();

I have defined relatioships in models but how can i write complex queries in Eloquent way

I have a query in existing application now i need to update query in eloquent way i have the following structure of my relationships how can i write the following query in eloquent way
Controller Query that i want to change in eloquent way
foreach ($data['Divisions'] as $sections) {
$SecQry1 = "SELECT sections.id, sections.division_id, sections.code, sections.name ,specifications.description
from specifications inner JOIN sections on specifications.section_id=sections.id where specifications.status='active'
AND specifications.manufacturer_id = $user->id AND sections.division_id=" . $sections->id . " group by sections.id";
$SectionsDivision1 = DB::select($SecQry1);
foreach ($SectionsDivision1 as $key => $selectionDiv) {
array_push($selectionDiv_array1, $selectionDiv);
}
}
class Specification extends Model {
protected $table = 'specifications';
public function section()
{
return $this->belongsTo('App\Section');
}
}
class Section extends Model {
protected $table = 'sections';
public function specifications()
{
return $this->hasMany('App\Specification', 'section_id');
}
public function division()
{
return $this->belongsTo('App\Division');
}
}
class Division extends Model {
protected $table = 'divisions';
protected $fillable = array('name', 'description', 'code','status');
public function sections()
{
return $this->hasMany('App\Section', 'division_id');
}
}
0 => {#1063 ▼
+"id": 1
+"division_id": 1
+"code": "03 01 00"
+"name": "Maintenance of Concrete"
+"description": null
}
]
You dont need relations for this specific query, you could use Laravel Eloquent with join like so:
$SectionsDivision1 = Specification::join('sections', 'specifications.section_id', '=', 'sections.id')
->where([
'specifications.status' => 'active',
'specifications.manufacturer_id' => $user->id,
'sections.division_id' => $sections->id
])->select('sections.id', 'sections.division_id', 'sections.code', 'sections.name', 'specifications.description')
->groupBy('sections.id');
I hope it helps

Laravel Eloquent populates collection with id 1 always

I have a project on laravel 5.
I wrote an SQL to select games from database, and after executing it, I got models collection, where every model has id = 1.
This is my query:
select * from `games` left join `game_vendors` on `games`.`vendor_id` =
`game_vendors`.`id` where `game_vendors`.`name` != 'some_vendor' and
`games`.`id` not in (1,2,3,4,5,6,7,8,9,10,11,12);
checked this query in mysql terminal - all is fine, id's are correct, but on postman or in the browser, I got this
array(2021) {
[0]=>
array(32) {
["id"] => int(1)
[1]=>
array(32) {
["id"] => int(1)
...
...
...
[24]=>
array(32) {
["id"] => int(1)
Model class contains this:
class Game extends Model {
protected $table = 'games';
public function vendor()
{
return $this->hasOne('App\GameVendor', 'vendor_id', 'id');
}
Use Laravel Eloquent Relationship and "WHERE NOT IN"
Update Model as
class Game extends Model {
protected $table = 'games';
public function vendor()
{
return $this->hasOne('App\GameVendor', 'vendor_id', 'id')->where('name', '!=' ,'some_vendor');
}
And use Eloquent as
$games = Game::whereNotIn('id',[1,2,3,4,5,6,7,8,9,10,11,12])->get();
foreach($games as $game){
$game->vendor->name
}

Phalcon DB Criteria in Model ORM

In Phalcon model is there a way to use SQL "IN" condition and other database criteria? For example, i want to execute this query in phalcon
SELECT user_fullname, user_email FROM tbl_users WHERE user_id IN (1,2,3,4,5)
I know you can use query builder but I want it to be ORM. I want a method in my model getUsersByIds($userIds, $columnsToSelect) that will accept an array of userids and columns that you want to fetch in the table.
See my model below
<?php
use Phalcon\Mvc\Model;
class User extends Model
{
/**
*
* #var integer
*/
public $user_id;
/**
*
* #var string
*/
public $user_email;
/**
*
* #var string
*/
public user_phone;
/**
*
* #var string
*/
public user_fullname;
public function initialize()
{ $this->hasMany('user_id','Store\Bag','user_id');
}
public function getSource()
{
return "tbl_user";
}
public function find($parameters = null)
{
return parent::find($parameters);
}
public function findFirst($parameters = null)
{
return parent::findFirst($parameters);
}
/**
* I want to execute this query in my model
* SELECT user_fullname,user_email from tbl_user where user_id IN (1,2,3,4,5);
*/
public function getUsersByIds($ids=array(), $columns=array())
{
if(!is_array($ids))
$ids = array($ids);
if(!is_array($columns))
$columns = array($columns);
...................................
.........................
..............
}
}
There are two ways of doing this:
Method 1: inWhere('columnName', array('columnValues'))
public function getUsersByIds(array $userIds, $columnsToSelect = '') {
return self::query()
->inWhere('id', $userIds)
->columns($columnsToSelect ?: '*')
->execute();
}
This one goes in your User model
Method 2: conditions => 'id IN ({ids:array})
User::find(['id IN ({ids:array})',
'columns' => $columnsToSelect,
'bind' => array('ids' => $userIds)]);
I am typing on my mobile, so there might be a typo in there.

Edit profile page with 3 tables - Yii frameworks

I am new on Yii framework, so please i need some help where to start.
What i need is, action and module to display a form to a user, which his will be able to edit is own profile (with profile picture), so i have 3 table
user_account || user_personal || user_general
how can i build a form that insert and update those 3 table at once?
i try this:
This is what i did, but its still not saving the data even into 1 table.
public function actionUpdate() {
$model = new ProfileUpdate();
if(isset($_POST['ProfileUpdate']))
{
$model->attributes = $_POST['ProfileUpdate'];
if($model->validate())
{
$account = new Profile();
$account->userid = Yii::app()->user->id;
$account->name = $model->name;
$account->website = $model->website;
$account->category = $model->category;
$account->save();
$this->redirect('profile');
}
}
model:
class Profile extends CActiveRecord
{
public $userid;
public $name;
public $website;
public $category;
public static function model()
{
return parent::model(__CLASS__);
}
public function tableName()
{
return 'userinfo';
}
public function primaryKey()
{
return 'id';
}
public static function userExists($user)
{
return self::model()->countByAttributes( array('username'=>$user) ) > 0;
}
}
You can use all three models in a single function
for example:
In create function
$model_account = new user_account;
$model_personal= new user_personal;
$model_general = new user_general;
$this->render('create',array(
'model_account'=>$model_account, 'model_personal' => $model_personal, 'model_general' => $model_general
));
here the all three models pass by render to create page.
in form page you can use the every model attributes as fields
Like this
echo $form->textField($model_account,'account_name');
echo $form->textField($model_personal,'email');
echo $form->textField($model_general,'address');
In create function / Update function
$model_account->attributes = $_POST['user_account'];
$model_personal->attributes = $_POST['user_personal'];
$model_general->attributes = $_POST['user_general'];
if($model_account->validate() && $model_personal->validate() && $model_general->validate())
{
$model_account->save();
$model_personal->save();
$model_general->save();
}