I need some help to make a query.
Database tabless
Example:
The user inserts a actor name(name and surname) and i need to loop over all the movies and then retrieve which category has more occurrences.
I need some help to make the query(this one is only a sketch):
$src=array("Leonardo","DiCaprio");
$film2=film::with('category')->with('actor')->wherehas('actor', function($q) use($src){
$q->where('first_name', $src[0])->where('last_name', $src[1]);
})->wherehas('category', function($qr){
$qr->groupBy('name')->orderBy('name', 'DESC');
})->FIRST();
model Film:
class film extends Model{
protected $table = "film";
protected $primaryKey = 'film_id';
public $timestamps = false;
use HasFactory;
protected $sql=['film_id', 'title', 'length'];
public function category(){
return $this->belongsToMany(category::class,'film_category', 'film_id', 'category_id');
}
public function actor(){
return $this->belongsToMany(actor::class,'film_actor', 'film_id', 'actor_id');
}
}
model Actor:
class actor extends Model{
protected $primaryKey = 'actor_id';
public $timestamps = false;
use HasFactory;
protected $sql=['actor_id', 'first_name', 'last_name'];
}
model Category:
class category extends Model{
protected $table = "category";
protected $primaryKey = 'category_id';
public $timestamps = false;
use HasFactory;
protected $sql=['category_id','name'];
public function film(){
return $this->belongsToMany(film::class,'film_category', 'category_id', 'film_id');
}
}
Here is the solution:
In Actor.php add Join
public function filmActor(){
return $this->hasMany(FilmActor::class, 'actor_id','actor_id');
}
Find the actor with filmActor join table
$src=array("Leonardo","DiCaprio");
$actor=Actor::whereHas('filmActor')->where(['first_name' => $src[0],'last_name'=> $src[1]])->first();
Put film_id in the array
foreach($actor->filmActor as $film){
$filmIds[]=$film->film_id;
}
Get FilmCategory who have filmIds
$filmCategory=FilmCategory::whereIn('film_id',$filmIds)->get();
Put category_id in the array
foreach($filmCategory as $category){
$categoryIds[]=$category->category_id;
}
Count how much is duplicate category_id
$count =array_count_values($categoryIds);
Get the higher counted $max = max($count);
Get the key of max which is category_id $key = array_search($max, $count);
Here is the category who has more occurrences.
$category=Category::where('category_id',$key)->first();
Related
sold_items:
id order_id customer_id name
-- -------- ----------- ----
1 5 14 An object
orders:
id po_num
-- ------
... ...
5 123
customers:
id name
-- ----
... ...
14 John Doe
A SoldItem has an order_id and a customer_id.
I'm trying to define a hasOne relationship between an Order and its Customer through the SoldItem without having to insert a customer_id column in the Order model's table.
hasOneThrough seemed to be the solution but I couldn't figure out where to go from there, or is that even the answer?
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
public $timestamps = false;
protected $guarded = ['id'];
public function sold_items()
{
return $this->hasMany('App\SoldItem');
}
public function customer()
{
// return $this->hasOneThrough();
}
}
for Customer model
{
public function sold_items()
{
return $this->hasMany('App\SoldItem');
}
}
for Order model
{
public function sold_items()
{
return $this->hasOne('App\SoldItem');
}
}
for SoldItem model
{
public function customer()
{
return $this->belongsto('App\Cutomer');
}
public function order()
{
return $this->belongsto('App\Order');
}
}
I prefer working on their relationship first then and use with() function to get their values.
use App\Customer;
$customer = Customer::with('sold_items','sold_items.order')->get();
I ended up making the Customer an attribute of the Order through its sold_items with:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
public $timestamps = false;
protected $guarded = ['id'];
public function sold_items()
{
return $this->hasMany('App\SoldItem');
}
public function getCustomerAttribute()
{
return $this->sold_items->first()->customer;
}
}
I have 3 models: User, Query, Offer. The relation is that user has many queries and query has many offers.
In controller I use $queries=User->query()->get(); (query() is a hasMany method in User model) and pass it to view as parameter. In view I want to display a table of queries from single user and count all offer made to each query.
Actually what I want to get, is a nested object $queries like
user:
query1:
offer1
offer2
query2:
offer3
offer4
How it should be coupled in models and how to use it in controller and view?
You could have something like:
Class User extends Model{
protected $table = 'users';
public function query(){
return $this->hasMany('App\Query');
}
}
Class Query extends Model{
protected $table = 'queries';
public function offer(){
return $this->hasMany('App\Offer');
}
public function user(){
return $this->belongsto('App\User');
}
}
Class Offer extends Model{
protected $table = 'offers';
public function query(){
return $this->belongsTo('App\Query');
}
}
Then in your controller you can have something like this:
public function showUser($id){
$user = User::with('query.offer')->find($id);
return View::make('user')->with('user', $user);
}
Then in your view you could have something like:
#foreach($user->query as $query)
{{$query->title}}
#foreach($query->offer as $offer)
{{$offer->title}}
{{$offer->amount}}
#endforeach
#endforeach
I want to be able to display attributes from a table anywhere in my application and have them be edited by the user. This means the data will come from a row in a database. Each column has a default value which can be changed by the user if they so choose.
The table columns may look like this:
| id | admin_id | practitioner | practitioners | student | students | and so on ...
Here is my model:
class Lang_trans_model extends CI_Model {
public function get_lang_trans($admin_id){
$this->db->where('admin_id', $admin_id);
$query = $this->db->get('lang_trans');
return $query->row();
}
Here is my MY_Controller:
class MY_Controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('key_items_model');
$this->load->model('lang_trans_model');
foreach ($this->key_items_model->get_key_items() as $result){
$this->label[$result->key] = $result->value;
}
//$admin_id = $this->session->userdata('admin_id');
$admin_id = 3;
$lang = $this->lang_trans_model->get_lang_trans($admin_id);
//not sure what should go here????
//I want to be able to use $lang->practitioner; to be able to have practitioner, or the edited attribute to show on the page
var_dump($lang);
// produces the following:
//object(stdClass)[26]
//public 'id' => string '3' (length=1)
//public 'admin_id' => string '3' (length=1)
//public 'practitioner' => string 'blah' (length=4)
//public 'practitioners' => string 'blahplural' (length=10)
How do I finish the MY_Controller to be able to use these data fields anywhere in my application?
I do not mind using object oriented syntax or array syntax. Whichever is easier. I just can not figure out how to display the fields without using a foreach statement in every view. I want to call the data with the $lang->practitioner; format in the view.
Thanks in advance.
Declare parent class properties. Than call it from child class:
class MY_Controller extends CI_Controller
{
public $lang;//parent variable declared
public function __construct()
{
parent::__construct();
$this->load->model('key_items_model');
$this->load->model('lang_trans_model');
foreach ($this->key_items_model->get_key_items() as $result) {
$this->label[$result->key] = $result->value;
}
//$admin_id = $this->session->userdata('admin_id');
$admin_id = 3;
//dedicating value to variable
$this->lang = $this->lang_trans_model->get_lang_trans($admin_id);
}
}
Child controller:
class Practitioners extends MY_Controller
{
public function __construct()
{
parent::__construct();
// no need to call model if it is called in parent controller
}
public function index()
{
var_dump($this->lang);
}
}
I'm newbie on Zend Framework, I created DbTable , my primary key is id , and my table name is user:
<?php
class Application_Model_DbTable_User extends Zend_Db_Table_Abstract
{
protected $_name = 'user';
protected $_primary = 'id';
}
after that ,I reviewed Abstract.php(Db/Table/Abstract.php) and I found out that I had to use insert(array $data), so I created a model: (Register.php)
<?php
class Application_Model_Register
{
public function CreateUser($array)
{
$dbTableUser = new Application_Model_DbTable_User();
$dbTableUser -> insert($array);
}
}
and finally , in my Controllers , I created IndexController.php
<?php
class IndexController extends Zend_Controller_Action
{
public function init()
{
/* Initialize action controller here */
}
public function indexAction()
{
$register = new Application_Model_Register();
$register-> CreateUser(array(
'username'=>'test'));
}
}
It works correctly , but I have no idea about Select, How I select query from user table?
our controller should have to be like below
<?php
class IndexController extends Zend_Controller_Action
{
public function getdataAction()
{
$register = new Application_Model_Dbtable_Register();
$register->getListOfUser();
}
}
Now your model should have to be like this,
<?php
class Application_Model_DbTable_Register extends Zend_Db_Table_Abstract
{
protected $_name = 'user';
protected $_primary = 'id';
public function getListOfUser()
{
$db = Zend_Db_Table_Abstract::getDefaultAdapter();
$select = $db->select()
->from($_name,array('*'))
->where(1);
$data = $db->query($select)->fetchAll();
return $data;
}
}
I'm working with the following models: Game, User and Player where Player extends User. In this case Game and Player have a relationship of N:N and User extends Confide. So code stands like:
app/models/Game.php
<?php
class Game extends Eloquent {
protected $guarded = array();
protected $table = 'users';
public $timestamps = false;
public function players(){
return $this->belongsToMany('Player');
}
}
app/models/User.php
<?php
use Zizaco\Confide\ConfideUser;
class User extends ConfideUser {
protected $table = 'users';
public $timestamps = false;
protected $hidden = array('password');
//Here go original Confide functions
}
app/models/Player.php
<?php
class Player extends User{
public function games(){
return $this->belongsToMany('Game');
}
}
I've populated the pivot table called game_player. As player extends user, pivot table is like this:
game_player
id
game_id
user_id
But if I run this super simple example I have an error:
$game = Game::find($gameId);
$player = $game->players(); //Error in this line
Error
Call to undefined method Illuminate\Database\Query\Builder::players()
I'm confused because I'm not having the error about pivot table was not found so I could think relationship is created fine.
On the other hand if I var_dump games var I obtain:
var_dump($game)
object(Game)[181]
protected 'table' => string 'games' (length=5)
//more var info about DB
protected 'relations' =>
array (size=0)
empty
protected 'hidden' =>
array (size=0)
empty
protected 'visible' =>
array (size=0)
empty
protected 'guarded' =>
If relationship would be created fine... shouldn't relations var have any data?
Thanks!
Just pointing out somethings that could solve the problem:
Your Game.php has the wrong table name.
When you get players, the line should be:
$game = Game::with('players')->find($gameId);
$player = $game->players;