I've been trying to convert the following query to an eloquent model query/raw database query. I have limited knowledge of laravel and I've come to a stop.
select
status,
(SELECT count(*) FROM active_call_statuses WHERE active_call_id = 'CA3a77245ab0eac10f8cf3aa8e7c8f9a91') AS total
from
active_call_statuses
left JOIN
active_calls ON active_calls.parent_call_id = active_call_statuses.active_call_id
where
status IN('in-progress', 'completed', 'ringing', 'answered', 'busy', 'failed', 'no-answer')
and
active_calls.parent_call_id = 'CA3a77245ab0eac10f8cf3aa8e7c8f9a91'
the pupose of the query is to select all columns with the given call status and count the total of status entries associated to the current call via its id in a sub query.
The query does what it's supposed to in mysql as far as i can see but I dont know how to convert this to an eloquent query.
The active_call_statuses table and active_calls table are linked to eachother via a one-to-many relationship on parent_call_id in eloquent respectively like so.
class ActiveCall extends Model
{
/**
* #var mixed
*/
public $timestamps = false;
/**
* #var array fillable properties
*/
protected $fillable = ['user_id', 'conference_id', 'parent_call_id'];
/**
* #return mixed
*/
public function statuses()
{
return $this->belongsToMany('app\ActiveCallStatus');
}
}
class ActiveCallStatus extends Model
{
/**
* #var bool timestamps enabled
*/
public $timestamps = false;
/**
* #var array fillable properties
*/
protected $fillable = ['active_call_id', 'user_id', 'status'];
/**
* #return mixed
*/
public function activeCall()
{
return $this->belongsTo('app\ActiveCall');
}
}
I've tried wraping the query in a DB::select with a DB::raw, calling a table with the DB->table(...)->selectRaw(...) .etc method by binding the parameters to the selectRaw aliased with :id but everything resulted in database errors invalid parameter number or other errors.
This is my last attempt:
processedUsers = DB::table('active_call_statuses')->select(
DB::raw("
SELECT
user_id,
status,
(SELECT count(*) FROM active_call_statuses WHERE active_call_id = :id) AS total
FROM
active_call_statuses"),
['id' => $activeCall->parent_call_id])
->whereIn('status',"('in-progress', 'completed', 'ringing', 'answered', 'busy', 'failed', 'no-answer')")
->where("active_calls.parent_call_id", $activeCall->parent_call_id);
which resulted in:
[2018-03-19 12:33:45] local.ERROR: Invalid argument supplied for foreach() {"exception":"[object] (ErrorException(code: 0): Invalid argument supplied for foreach() at C:\\wamp64\\www\\Stage\\LanthopusX\\voip\\vendor\\laravel\\framework\\src\\Illuminate\\Database\\Query\\Builder.php:763)
Try this:
ActiveCallStatus::leftJoin('active_calls', 'active_calls.parent_call_id', '=', 'active_call_statuses.active_call_id')
->whereIn('status', ['in-progress', 'completed', 'ringing', 'answered', 'busy', 'failed', 'no-answer'])
->where('active_calls.parent_call_id', $activeCall->parent_call_id)
->select('status')
->selectRaw('(SELECT count(*) FROM active_call_statuses WHERE active_call_id = ?) AS total', [$activeCall->parent_call_id])
->get();
Related
I am trying to fetch the data from table name pos_receipt. It has a child table which contains a column receipt_id of pos_receipt primary key. I just want to return empty if child table has no relationship with parent table. Right now its returning the data with empty array of parent if there is no relationship. It should return empty array if there is no relationship in child table
Here is the query :
$options = PosReceipt::with([
'transferBranch' => function ($query) {
$query->where('branch_id',2);
},
])
->where('receipt_no','LIKE','%'.$filters->keyword.'%')
->whereDate('receipt_date','>=', $date1)
->whereDate('receipt_date','<=', $date2)
->where('type', 'TRN')
->limit(20)
->offset($request->start)
->orderBy('id','DESC')
->get();
AND THE RELATIONSHIP FOR THE MODEL FOR transferBranch relation is
//MODEL CALSS OF PosReceipt
public function transferBranch()
{
return $this->hasMany(TransferStore::class,'receipt_id');
}
incase if someone needs a solution
$options = PosReceipt::with([
'transferBranch'
])
->whereHas("transferBranch",function($q) use($filters){
$q->where("branch_id","=",$filters->storeID);
})
The hasMany method has 3 arguments.
/**
* Define a one-to-many relationship.
*
* #param string $related
* #param string|null $foreignKey
* #param string|null $localKey
* #return \Illuminate\Database\Eloquent\Relations\HasMany
*/
public function hasMany($related, $foreignKey = null, $localKey = null)
Try changing to
return $this->hasMany(TransferStore::class,'receipt_id','id');
And make sure youre using this at the top of the model.
use Illuminate\Database\Eloquent\Relations\HasMany;
I want show related table columns (customers.name) in all select of model (User) laravel.
I use accessor laravel.
user table:
id name customer_id
1 hassan 1
customer table:
id name
1 customer1
now use
$user = Auth::user();
return $user;
I want show:
id: 1,
name: "hassan",
customer_id: {
id: 1,
name: "customer1"
}
but show this error:
Failed calling App\User::jsonSerialize()
class User extends Authenticatable
{
use EntrustUserTrait;
/**
* Get the user's customer name.
*
* #param string $value
* #return array
*/
public function getCustomerIdAttribute($value)
{
return [
'id' => $value,
'name' => $this->customer->name
];
}
/**
* The attributes that should be casted to native types.
*
* #var array
*/
protected $casts = [
'customer_id' => 'array',
];
/**
* Get the customer record associated with the user.
*/
public function customer()
{
return $this->belongsTo(Customer::class);
}
}
So, you want to get customer name from users table based on customer_id in users.
In User.php model
public function customer(){
return $this->hasOne(Customer::class,'id','customer_id');
}
Then,
$user = Auth::user();
$user->customer;
Seems like this is a known issue (https://github.com/FrozenNode/Laravel-Administrator/issues/879).
I would suggest, after getting your ::all() result, you loop through it and call $user->customer.
foreach($result as $user) $user->customer;
You should remove the $casts property. There is no way an integer can be converted to an array directly from the database, as the casts property is immediately used when selecting attributes from the database.
Also, there is no need for the getCustomerIdAttribute method, as the customer will be automatically be converted to a fictive attribute called 'customer'.
In short: just defining the customer relationship is enough. It should return the requested output except for it being called 'customer' instead of 'customer_id'.
I find answer.
public function getCustomerNameAttribute()
{
return $this->attributes['customer_name'] = ($this->customer ? $this->customer->name : null);
}
/**
* The accessors to append to the model's array form.
*
* #var array
*/
protected $appends = [
'customer_name',
];
Shoot me down if I this is a silly question, but I am really struggling to get this all() function working for me. It is returning empty list for me. Any help will be highly appreciated. I have got 2 rows in the newsletters table
Model looks like this -
<?php
use Illuminate\Auth\UserTrait;
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableTrait;
use Illuminate\Auth\Reminders\RemindableInterface;
class Newsletters extends Eloquent {
//use UserTrait, RemindableTrait;
use SoftDeletingTrait; // <-- Use This Insteaf Of protected $softDelete = true;
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'newsletters';
/**
* The attributes excluded from the model's JSON form.
*
* #var array */
protected $guarded = array('newsletterId');
protected $fillable = array('name', 'subject','from_email','from_name');
public static $rules = array(
'name' => 'required|min:5',
'subject' => 'required|min:5',
'from_email' => 'required|email',
'from_name' => 'required'
);
}
My call in the controller is like this -
<?php
class newslettersController extends \BaseController {
/**
* Display a listing of the resource.
*
* #return Response
*/
public function index()
{
//$newsletters = Newsletters::paginate(3);
$newsletters = Newsletters::all();
echo $newsletters;exit();
return View::make('newsletters.index', compact('newsletters'));
}
Any value - even 0000-00-00 00:00:00 - in the deleted_at column tells Laravel that the item has been deleted. Change your default value for that column to NULL or new items will be flagged as deleted on creation.
The $table->softDeletes() Schema function does this automatically if you use it in a migration.
As soon as you use the SoftDeletingTrait a global scope will be applied to every query with your model so all records where deleted_at is not NULL will be ignored.
Illuminate\Database\Eloquent\SoftDeletingScope:
public function apply(Builder $builder)
{
$model = $builder->getModel();
$builder->whereNull($model->getQualifiedDeletedAtColumn()); // <<-- this
$this->extend($builder);
}
Change the default of your deleted_at column to NULL and update the existing records to be NULL as well.
If you are sure newsletters is the correct table name as #Ray said.
Try this:
$newsLetters = DB::table('newsletters')->get();
hey guys im new in laravel and i was trying to insert into my pivot table. i have this structure in my database
the departments table belongs to many categories and same as category so i have this models
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Departments extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'departments';
protected $fillable = ['department_name'];
public $timestamps = false;
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
public function categories()
{
return $this->belongsToMany('Categories');
}
}
use Illuminate\Auth\UserInterface;
use Illuminate\Auth\Reminders\RemindableInterface;
class Categories extends Eloquent {
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'categories';
protected $fillable = ['name'];
public $timestamps = false;
/**
* The attributes excluded from the model's JSON form.
*
* #var array
*/
public function department()
{
return $this->belongsToMany('Departments');
}
}
then i have a query in my controller like this
$messages = array(
'required' => 'Please Fill the required field',
'unique' => 'Name Already exist'
);
$catName = Input::get('categoryName');
$deptId = Input::get('deptId');
$validation = Validator::make(Input::all(),[
'categoryName' => 'required|unique:categories,name' ], $messages);
if($validation->fails()){
return array('error' =>$validation->messages()->all() );
}else{
$findDepartment = Departments::find($deptId);
$saveCat = $findDepartment->categories()->insert(array('name' => $catName));
}
but then when i checked the tables it adds up on the categories table but nothing is added in the category_department. do i miss any codes? and also i had an error last time I was trying to migrate my pivot table the error was this.
can you help me guys on what i am missing? tnx for the help in advanced.
First, you should name your model classes as singular: Category, Department.
Then try to declare your relationships with the pivot table name:
public function categories()
{
return $this->belongsToMany('Category', 'category_department');
}
and
public function departments()
{
return $this->belongsToMany('Departments', 'category_department');
}
now, to insert new data, try attach:
$findDepartment = Department::find($deptId);
$category = Category::where('name', '=', $catName)->first();
$saveCat = $findDepartment->categories()->attach($category->id);
I can't Insert into this table and this drives me crazy
This is the error Msg I get
var_export does not handle circular references
open: /var/www/frameworks/Scout/vendor/laravel/framework/src/Illuminate/Database/Connection.php
* #param Exception $e
* #param string $query
* #param array $bindings
* #return void
*/
protected function handleQueryException(\Exception $e, $query, $bindings)
{
$bindings = var_export($bindings, true);
$message = $e->getMessage()." (SQL: {$query}) (Bindings: {$bindings})";
Here is my Full Mode
<?php
namespace Models;
use Illuminate\Database\Eloquent\Collection;
class Student extends \Eloquent
{
/**
* The database table used by the model.
*
* #var string
*/
protected $table = 'students';
/**
* The rules used to validate new Entry.
*
* #var array
*/
protected $newValidationRules = array(
'studentCode' => 'unique:students,code|numeric|required',
'studentName' => 'required|min:2',
'dateOfBirth' => 'date',
'mobile' => 'numeric'
);
/**
* Relation with sessions (Many To Many Relation)
* We added with Created_at to the Pivot table as it indicates the attendance time
*/
public function sessions()
{
return $this->belongsToMany('Models\Session', 'student_session')->withPivot('created_at')->orderBy('created_at', 'ASC');
}
/**
* Get Student Subjects depending on attendance,
*/
public function subjects()
{
$sessions = $this->sessions()->groupBy('subject_id')->get();
$subjects = new Collection();
foreach ($sessions as $session) {
$subject = $session->subject;
$subject->setRelation('student', $this);
$subjects->add($subject);
}
return $subjects;
}
/**
* Insert New Subject
* #return Boolean
*/
public function insertNew()
{
$this->validator = \Validator::make(\Input::all(), $this->newValidationRules);
if ($this->validator->passes()) {
$this->name = \Input::get('studentName');
$this->code = \Input::get('studentCode');
if ($this->save()) {
return \Response::make("You have registered the subject successfully !");
} else {
return \Response::make('An Error happened ');
}
} else {
Return $this->validator->messages()->first();
}
}
}
I am just trying to insert a new row with three Columns (I call the insertNew function on instance of Student)
1- ID automatically incremented
2- Special Code
3- Name
And I got this above Msg
What's I have tried till now :
removing all relations between from this model and other models
that has this one in the relation
Removed the validation step in insertNew()
Removed the all Input class calls and used literal data instead.
note that I use similar Inserting function on other Models and it works flawlessly
Any Comments , Replies are appreciated :D
Solution
I solved it and the problem was that I am accessing the validator
$this->validator = \Validator::make(\Input::all(), $this->newValidationRules);
And it was because I forgot that
/**
* The validator object.
*
* #var Illuminate\Validation\Validator
*/
protected $validator;
I had a similar problem. But to me, changing this code:
if ($this->validator->passes()) {
$this->name = \Input::get('studentName');
$this->code = \Input::get('studentCode');"
to this:
if ($this->validator->passes()) {
$this->setAttribute ("name" , \Input::get('studentName'));
$this->setAttribute ("code" , \Input::get('studentCode'));"
solved it.