Laravel Eloquent populates collection with id 1 always - sql

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
}

Related

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 Convert Mysql query to Eloquent

I'm new to Laravel and I can write simple eloquent queries but have no idea how to convert this query to eloquent. Can anyone give any idea, is it possible to convert this to eloquent or I have to write raw query?
"Select categories.id, categories.name, Sum(likes.liked) as liked
FROM categories, likes
WHERE likes.material_id IN (SELECT category_material.material_id
FROM category_material
WHERE category_material.category_id = categories.id)
GROUP BY categories.id";
Here my Models
class Material extends Model
{
public function categories(){
return $this->belongsToMany(Category::class,'category_material');
}
public function likes(){
return $this->hasMany(Like::class);
}
////////////////////////////////////////////////////////////
class Like extends Model
{
protected $table = 'likes';
public function user(){
return $this->belongsTo(User::class);
}
public function material(){
return $this->belongsTo(Material::class);
}
//////////////////////////////////////////////////////
class Category extends Model
{
public function materials(){
return $this->belongsToMany(Material::class,'category_material');
}
You can define a likes relationship in your Category model like so:
public function likes()
{
return $this->belongsToMany(Like::class, 'category_material', 'category_id', 'material_id', 'id', 'material_id');
}
Then to achieve what you're after with Eloquent you can use a mixture of has() and withCount, however, we're going to modify the withCount call to return a sum() instead:
$catrgories = Category::has('likes')->withCount([
'likes as liked' => function ($query) {
$query->select(DB::raw('SUM(likes.liked)'));
},
])->get();
If you're wanting to return categories that don't have any likes you can remove the has() method, and introduce the COALESCE() function to your raw query:
$catrgories = Category::withCount([
'likes as liked' => function ($query) {
$query->select(DB::raw('COALESCE(SUM(likes.liked), 0)'));
},
])->get();
Alternatively, you could simply load the necessary relationships and then use that fact that Eloquent returns collection to get the value after you've retrieved the results from the database:
$categories = Category::with('materials.likes')->get()->map(function ($item) {
$item->setAttribute('liked', $item->materials->map(function ($item) {
return $item->likes->map->sum('liked')->sum();
})->first());
$item->unsetRelation('materials');
return $item;
});
This would mean that you don't have to add the custom relationship.

Laravel 5 joining multiple tables

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');

Phalcon query builder can't get joined table data

I have 2 table 'sanpham' and 'danhmuc'. I use phalcon query builder to get data from 2 tables.
$laytin = $this->modelsManager->createBuilder()
->from("sanpham")
->innerJoin('danhmuc','sanpham.danhmuc=danhmuc.sodanhmuc')
->where('sanpham.sosanpham = '.$id.'')
->getQuery()
->getSingleResult();
$breadcrumbs = array('/' => Tool::getTranslation()->_('trangchu'),"/Loai-san-pham/".$laytin->tendep."/".$laytin->sodanhmuc => $laytin->tendanhmuc,'' => $laytin->tieudesanpham );
The query runs, but $laytin->tendep, $laytin->sodanhmuc, $laytin->tendanhmuc in 'danhmuc' table doesn't display. Every column in 'sanpham' table (such as: $laytin->tieudesanpham) displays properly.
You can add specific columns with:
$this->modelsManager->createBuilder()->columns('danhmuc.tend‌​ep, danhmuc.sodanhmuc')
With this method you will have to add each column you want in your output. QueryBuilder docs.
Another method is to query the Sanpham model.
For example:
class Sanpham extends \Phalcon\Mvc\Model
{
public static function findSomething($something)
{
// this is your actual query, it replaces the queryBuilder
return self::query()
->where('sanpham.sosanpham = :id:', ['id' => $something])
->innerJoin('danhmuc', 'sanpham.danhmuc = danhmuc.sodanhmuc')
->execute()->getFirst();
}
public function initialize()
{
// define the relation to danhmuc
$this->belongsTo('danhmuc', 'danhmuc', 'sodanhmuc');
}
}
class Danhmuc extends \Phalcon\Mvc\Model
{
public function initialize()
{
// there are other options besides "hasMany", like "hasOne".
// this is your relation to sanpham
$this->hasMany('sodanhmuc', 'sanpham', 'danhmuc');
}
}
class YourController extends \Phalcon\Mvc\Controller
{
public function testAction()
{
// get your first record in Sanpham matching "12345"
$sanpham = Sanpham::findSomething(12345);
// from your Sanpham object, get the related danhmuc object.
// this works because we defined the relations (belongsTo and hasMany)
$danhmuc = $sanpham->getRelated('danhmuc');
// now you have access to the values of danhmuc via the $danhmuc variable
$breadcrumbs = [
'/' => Tool::getTranslation()->_('trangchu'),
"/Loai-san-pham/" . $danhmuc->tendep => $danhmuc->tendanhmuc,
'' => $danhmuc->tieudesanpham,
];
}
}
Check the Phalcon model docs for more info on this.

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();
}