Laravel5 Eloquent custom method return array - laravel

I have a static method in my User model which counts something, i am using a raw statement:
static function countOrders($userId)
{
$sql = "SOME CUSTOM-COMPLICATED QUERY";
$result = \DB::select( \DB::raw( $sql ) );
return $result; // <-- toArray() ? returns Exception!
}
Somewhere in my controller:
$orders = User::countOrders(*USER-ID*);
How can I get an array with records as arrays and not objects without modifying the global configuration for the FETCH method?

You don't need to run toArray().
When executing raw queries select returns array, it's stated in the docs:
The select method will always return an array of results.
static function countOrders($userId)
{
$sql = "SOME CUSTOM-COMPLICATED QUERY";
$result = \DB::select( \DB::raw( $sql ) );
return $result;
}

Related

Merging two queries does not return all available records

I'm having trouble merging two query results into an array - the merged output contains all the records of one of the queries ($factsheets) but only the last record of the other ($actives) where there are usually at least 3 records "available" to return.
My controller's code is as follows:
public function show($pest)
{
$theactives = self::getActives($pest);
$thefactsheets = self::getFactsheets($pest);
$merged = $theactives->merge($thefactsheets);
$result = $merged->all();
return $result;
}
public function getActives($pest){
$actives = Active::where('pests.id',$pest)
->join("active_pest","actives.id","=","active_pest.active_id")
->join("pests","pests.id","=","active_pest.pest_id")
->select('ai', 'groupcode', 'risk', 'pest')
->orderBy('ai')
->get();
return $actives;
}
public function getFactsheets($pest){
$factsheets = Factsheet::where('pest_id',$pest)
->join("factsheet_pest","factsheets.id","=","factsheet_pest.factsheet_id")
->select('title', 'factsheets.id')
->orderBy('title')
->get();
return $factsheets;
}
Again, my expectation has exceeded my ability - what am I doing wrong here?
you can't merge objects of the result set. So, you have to convert your result into array first before the merge. Try the below script.
public function show($pest)
{
$theactives = self::getActives($pest);
$thefactsheets = self::getFactsheets($pest);
return array_merge($theactives, $thefactsheets);
}
public function getActives($pest){
return Active::where('pests.id',$pest)
->join("active_pest","actives.id","=","active_pest.active_id")
->join("pests","pests.id","=","active_pest.pest_id")
->select('ai', 'groupcode', 'risk', 'pest')
->orderBy('ai')
->get()->toArray();
}
public function getFactsheets($pest){
return Factsheet::where('pest_id',$pest)
->join("factsheet_pest","factsheets.id","=","factsheet_pest.factsheet_id")
->select('title', 'factsheets.id')
->orderBy('title')
->get()->toArray();
}
You can use union in laravel
example
$silver = DB::table("product_silver")
->select("product_silver.name"
,"product_silver.price"
,"product_silver.quantity");
$gold = DB::table("product_gold")
->select("product_gold.name"
,"product_gold.price"
,"product_gold.quantity")
->union($silver)
->get();
then
dd($gold);

Laravel - How to convert Stdclass object to Array

I'm facing this problem when use database in Laravel. How can i convert that to Array the most simpletest?
$data = DB::table('users')->get();
Please try this. this will return array of objects.
$result = json_decode(json_encode($data, true));
*Updated
if you want to convert all nested properties to the array, try this.
$result = json_decode(json_encode($data, true), true);
get() will return a collection. If you want to get an array of objects, use the toArray() method:
$data->toArray();
If you want to convert every object to an array too, do this:
$data->map(function($i) {
return (array)$i;
})->toArray();
I usually run into this problem when I use DB::select and manually write my sql:
$sql = 'SELECT *
FROM ba_pics ba
INNER JOIN pages pgs
ON ba.service_page_id = pgs.id';
$baPics = DB::select($sql);
$baPics = json_decode(json_encode($baPics, true), true);
return view('beforeAndAfter',['baPics'=>$baPics, 'lodata'=>'no lodata yet']);
Here is another way using PHP's array_map function:
$sql = 'SELECT *
FROM ba_pics ba
INNER JOIN pages pgs
ON ba.service_page_id = pgs.id';
$baPics = DB::select($sql);
$baPics = array_map(function($i) {
return (array)$i;
}, $baPics);
return view('beforeAndAfter',['baPics'=>$baPics, 'lodata'=>'no lodata yet']);

Codeigniter get database value in controller

This is my controller
function index($id=NULL)
{
$this->load->model('article');
$id= $this->uri->segment(3);
$data = array('article' => $this->article->show_a_article($id),
'sidebar' => $this->article->side_bar(9),
'related'=> $this->article->related_keyword($article_title),
);
echo $article->News_News_ID;
$this->load->view('page/baiviet',$data);
}
I want to get article_title value from table article and put it in related_workword() function.
Update model The show a article model is to get article detail. The second model is to get all article related to the chosen article.
function show_a_article($id)
{
$query= $this->db->get_where('news_news', array('News_News_ID'=>$id));
return $query->row();
}
function related_keyword($rkey)
{
$sql="SELECT `News_News_ID`,`News_News_Headline`,`News_News_thumb1` FROM `news_news` WHERE `news_tags` like '%$rkey%' ORDER BY `News_News_ID` desc LIMIT 10";
$query= $this->db->query($sql);
return $query->result();
}
Update: Igot it
echo $this->article->show_a_article($id)->News_News_Headline;
Call model method from controller
$article_title = $this->article->get_article_details($id)->article_title;
Add function in model to return data.
function get_article_details($id)
{
$query = 'select article_title from table where col = '.$this->db->escape($id);
return $this->db->query($query)->row();
}

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

How I can convert Object to String in laravel 4

I have a function in the model and I return it to a variable like the following
$books = DB::select('select * from books where category_id = 2');
return $books;
And Laravel Query Builder return an object.How I can convert it to the string from the controller? Have a function for that? Please let's me know.
What you get from this query
$books = DB::select('select * from books where category_id = 2');
If you do
var_dump($books);
You'll see that it's an array, not an object.
You need a big string with all your records? You can serialize it:
return serialize($books);
But you'll have to
unserialize($value);
to use it.
You need to use the values you get from that select? You can use foreach() on that array:
foreach($books as $book)
{
echo $book['name'];
}
Or you can do your select differently:
$books = Book::where('category_id',2)->get();
And do your foreach using the object notation:
foreach($books as $book)
{
echo $book->name;
}

Resources