Laravel ORM Relationship - laravel

Hello I have those 4 tables:
Products (id, name)
Params (id, name)
Product_Param (id, product_id, param_id)
Values (product_param_id, value)
I can get all product params:
public function params() {
return $this->belongsToMany('App\Models\Param', 'product_param')->withPivot('id', 'type1_id', 'type2_id');
}
Code:
foreach($products->params as $param) {
var_dump($param)
}
And now I need to get param value.
I wrote stupid code like this:
public static function getPPV($product_id, $param_id) {
$value = new \App\Models\ParamValue();
$value->value = NULL;
$value->id = NULL;
$pp = \App\Models\ProductParam::where('product_id','=',$product_id)->where('param_id','=',$param_id)->first();
if (!$pp) return $value;
$ppv = \App\Models\ProductParamValue::where('product_param_id','=',$pp->id)->first();
if (!$ppv) return $value;
$value->value = $ppv->productvalue->value;
$value->id = $ppv->productvalue->id;
return $value;
}
It works but I want use better solution with ORM. Param model:
public function val() {
$p = $this->hasOne('App\Models\ProductParam')->orderBy('id','desc')->where('product_id','=',$this->product_id);
$ppv = $p->getResults()->hasOne('App\Models\ProductParamValue');
$val = $ppv->getResults()->belongsTo('App\Models\ParamValue','param_value_id');
return $val;
}
But in Param Model I can't get Product ID ->where('product_id','=',$this->product_id) (we have Product_Param (id, product_id, param_id) and I get all rows from Product_Param.
Please help to write ORM.

This may be not what you're looking for, but have you tried implementing the value column in the Values table to be its own column in the Product_Params table? Then you could access each of the values by saying:
foreach($products->params as $param) {
var_dump($param->pivot->value);
}

Related

Search Query by Child field Eloquent relation

My Product Model is
public function IncomeRepo(){
return $this->hasMany(Income::class,'Product');
}
My Income Report Model Is
public function ProductData(){
return $this->belongsTo(Product::class,'Product','id');
}
My Query is
public function SearchIncomeData(Request $request){
$GetFromDate = $request->FromDate;
$GetToDate = $request->ToDate;
$ProductData = Product::with('IncomeRepo')->whereBetween('created_at', [$GetFromDate, $GetToDate])->get();
return view('Admin.Report.ProductSalesReport',compact('ProductData'));
}
When I return $ProductData it return products table created_at Data. BUT I nee Income table created_at data which be multiple
How can I get it?
My expectation show incomes table created_at data
If you want to filter data by child tables date then you need to use whereHas relationship.
$GetFromDate = $request->FromDate;
$GetToDate = $request->ToDate;
$ProductData = Product::with('IncomeRepo')
->whereHas('IncomeRepo',function($que) use($GetFromDate,$GetToDate) {
$que->whereBetween('created_at',[$GetFromDate, $GetToDate])})->get();
return view('Admin.Report.ProductSalesReport',compact('ProductData'));
In controller. (Use whereBetween)
public function SearchIncomeData(Request $request)
{
$GetFromDate = $request->FromDate;
$GetToDate = $request->ToDate;
$ProductData = Product::with(['IncomeRepo' => function ($query) use ($GetFromDate, $GetToDate)
{
$query->whereBetween('created_at', [$GetFromDate, $GetToDate]);
}
])->get();
return view('Admin.Report.ProductSalesReport', compact('ProductData'));
}
In view
foreach ($ProductData as $product)
{
foreach ($product->IncomeRepo as $income)
{
echo $income->created_at;
}
}

Error : Method Illuminate\Database\Eloquent\Collection::StudentInfo does not exist. (Laravel 5.6)

I am new to make join tables with Eloquent. I want to join 3 tables. But it shows me error. What's my mistake, if anyone notice it will be helpful for me. Here is tables....
In 1st table Applications(id,u_id,program_name) 2nd table StudentInfos(id,u_id,.....) 3rd table users(id,.....)
in Application model
public function StudentInfo()
{
return $this->hasOne('App\StudentInfo', 'u_id', 'u_id');
}
in StudentInfo model
public function User()
{
return $this->hasOne('App\user', 'u_id', 'id');
}
From controller
public function view_application($id)
{
$vu_data = Application::where('id', $id)->get();
$vu_data2 = $vu_data->StudentInfo()->get();
return $vu_data2;
}
$vu_data2 = $vu_data->StudentInfo()->get();
is returning a collection and not just a single Application Model. Change "get()" to "first()", and this will fix your first error. So change:
$vu_data = Application::where('id', $id)->get();
to
$vu_data = Application::where('id', $id)->first();
When you do get(), it returns a collection. You can do :
$vu_data = Application::findOrFail($id);
$student = $vu_data->StudentInfo;
$user = $student->User;

How to get all data in one column of database codeigniter?

I want to get all data in one column of the database (primary key) so that before I insert my data that is going to be inserted, I can check if its going to be duplicate or not.
Model:
public function getKeys() {
$this->db->select("key");
$this->db->from("database");
$result = $this->db->get();
return $result->result();
}
Controller:
public function Controler() {
$values = $this->MODEL_NAME->getKeys();
foreach ($values as $value) {
$array[] = $value->key;
}
# Compare new item to the current array
if (!(in_array($NEWITEM, $array))) {
# Insert
} else {
# Error catching
}
}
At insert time get all data from table.and then use condition on a particular field by which you want to check this data is already exist or not:

Error Number: 1066 Not unique table/alias: 'core_user'

I have 3 tables in a database.
core_user
core_company
ct_company
i want to join 2 tables core_user and core_company where foriegn key is cmp_id column..
but it shows an error.
Error Number: 1066
Not unique table/alias: 'core_user'
SELECT * FROM (core_user, core_user) JOIN core_company ON core_company.cmp_id = core_user.cmp_id WHERE usr_email = 'fahad#gmail.com' AND usr_password = '123456' AND cmp_name = 'corpoleave'
Filename: F:/xampp/htdocs/corpoLeave/application/models/loginmodel.php
Line Number: 10
here is my model. please help. thanks
<?php class LoginModel extends CI_Model{
public function login_valid($email,$password,$cname){
$q= $this->db->where(['usr_email'=>$email,'usr_password'=>$password,'cmp_name'=>$cname])
->from('core_user');
$this->db->join('core_company', 'core_company.cmp_id = core_user.cmp_id');
$q = $this->db->get('core_user')->result();
if($q->result()==true)
{
return $q->row()->user_id;
}
else{
return false;
}
}}
?>
In the Codeigniter Query Builder, the get() and from() methods perform similarly.
As seen on the Codeigniter docs:
get()
$query = $this->db->get('mytable');
// Produces: SELECT * FROM mytable
from()
$this->db->select('title, content, date');
$this->db->from('mytable');
$query = $this->db->get();
// Produces: SELECT title, content, date FROM mytable
Both the get("tablename") and from("tablename") methods effectively append FROM tablename to the built statement, looking something like this:
$this->db->select('title, content, date');
$this->db->from('mytable');
$query = $this->db->get('mytable');
// Produces: SELECT title, content, date FROM mytable FROM mytable
(Notice the double "FROM" statement)
You are getting the error because you are using both from() and get() with tablenames. You can either remove the from() statement, or remove the tablename from the get() statement.
This would look like:
<?php
class LoginModel extends CI_Model {
public function login_valid($email, $password, $cname) {
$this->db->where(['usr_email' => $email, 'usr_password' => $password, 'cmp_name' => $cname]);
$this->db->from('core_user');
$this->db->join('core_company', 'core_company.cmp_id = core_user.cmp_id');
$q = $this->db->get();
if ($q->result()) {
return $q->row()->user_id;
} else {
return false;
}
}
}

dropdownlist not working in yii

the thing is i have 3 models wherein model1 model2's xyz(pid) is invoked which fetches the all id's contain that pid ,know model3 have (id,name) for the model2 fetched ids(fk of model3 id) ,i have looped them ,$data should store the name,id and a list of all id,name must appear in the dropdown of model1 view create
but i get the error stating
CDbCommand failed to execute the SQL statement: SQLSTATE[42S22]: Column not found: 1054 Unknown column 'Array' in 'where clause'. The SQL statement executed was:
SELECT id,name
FROM table1
WHERE id = Array
model1
public function myabcDropDown()
{
$pid=Yii::app()->SESSION['pid'];
$sid=model2::model()->xyz($pid);
foreach($sid as $val) //line 0
{
$data=model3::model()->pqr($val);
$data.=$data;
}
//line 1
$datalist=CHtml::listData($data,'id','name');
return $datalist;
}
function in model3
public function pqr($val)
{
$sql="SELECT id,name
FROM table1
WHERE id = ".$val;
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$tts=$command->queryRow();
$result=array();
foreach($tts as $key=>$val1)
{
$result[]=$val1;
}
return $result;
}
function in model2
public function xyz($pid);
{
$sql="SELECT id
FROM table3
WHERE id = ".$pid;
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$tts=$command->queryAll();
$result=array();
foreach($tts as $key=>$val)
{
$result[]=$val;
}
return $result;
}
Please help I am losing my mind on it
$result of xyz() is an array of rows(which in turn are arrays of fields) not of fields since queryAll was used. Use queryRow instead.
You need to learn about queryScalar() as they can help you a ;lot. now looking into your code you can do this
public function xyz($pid);
{
$sql="SELECT id
FROM table3
WHERE id = ".$pid;
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$result=$command->queryColumn();
return $result;
}
Then
public function myabcDropDown()
{
$data=array();
$pid=Yii::app()->SESSION['pid'];
$sid=model2::model()->xyz($pid);
if(!empty($sid))
{
foreach($sid as $value)
{
$data[]=model3::model()->pqr($value);
}
$datalist=CHtml::listData($data,'id','name');
return $datalist;
}
else
{
throw new CHttpException('I got no result');
}
}
and then finally
public function pqr($val)
{
$criteria=new CDbCriteria;
$criteria->select='id,name';
$criteria->condition='id=:id';
$criteria->params=array(':id'=>$val);
$result=Table1::model->find($criteria);
return $result;
}
Information:-
queryScalar() = You should use it if you are sure that your query is going to return single result only. It will make you free from the headache of arrays.
queryColumn() = You should use it if your are going to select a single column values in your query. It will return you one dimensional array and hence making you free from the headache of multidimensional arrays.
This wrks
public function myabcDropDown()
{
$pid=Yii::app()->SESSION['pid'];
$sid=model2::model()->xyz($pid);
$datalist=CHtml::listData($sid,'id','name');
return $datalist;
}
public function xyz($pid);
{
$sql="select id ,name from table1 where id IN (SELECT id
FROM table2
WHERE pid = ".$pid.")";
$connection=Yii::app()->db;
$command=$connection->createCommand($sql);
$tts=$command->queryAll();
$result=array();
foreach($tts as $key=>$val)
{
$result[]=$val;
}
return $result;
}
and no need od pqr() any more

Resources