I am writing an app in laravel which displays this error SQLSTATE[42000]: Syntax error or access violation: 1066 Not unique table/alias: 'medicals' (SQL: select * from patients left join medicals on medicals.patients_id = patients.id left join medicals on medicals.trx_id = patient_referral.trx_id)
return Patients::where(function ($q) use ($startdate, $enddate, $id) {
$q->where("patient_referral.trx_id", $id);
})
->leftJoin("medicals", "medicals.patients_id", "=", "patients.id")
->leftJoin("medicals", "medicals.trx_id", "=", "patient_referral.trx_id")
->get();
Medical Model
class Medicals extends Model
{
protected $guarded = [];
public function patients()
{
return $this->belongsTo(Patients::class, "id", "patients_id");
}
public function tests()
{
return $this->belongsTo(Tests::class);
}
}
Patient Model
class Patients extends Model
{
protected $guarded = [];
public function medicals()
{
return $this->hasMany(Medicals::class);
}
public function patient_referral()
{
return $this->hasMany(PatientReferral::class);
}
}
Patient Referral Model
class PatientReferral extends Model
{
protected $guarded = [];
protected $table = "patient_referral";
public function patients()
{
return $this->belongsTo(Patients::class);
}
}
You are trying to join medicals table twice so in this case you need to provide unique alias to each instance and in join clause specify that alias for columns so that database will know the exact column from table to use in filter like
Patients::where(function ($q) use ($startdate, $enddate, $id) {
$q->where("patient_referral.trx_id", $id);
})
->leftJoin("medicals as a", "a.patients_id", "=", "patients.id")
->leftJoin("medicals as b", "b.trx_id", "=", "patient_referral.trx_id")
->get();
Related
I'm trying to build a small application where I am having three models, I want to sort the model by column inside the eager load relationship, for this I have a model named AssociatedCompany as:
class AssociateCompany extends Model {
protected $table = 'project_associate_company';
protected $fillable = [
'project_id', 'company_role_id', 'company_specialisation_id', 'company_id', 'link', 'file_name'
];
public function project()
{
return $this->belongsTo('App\Project','project_id','id');
}
public function companyRole()
{
return $this->belongsTo('App\Role', 'company_role_id','id');
}
}
and other model Role as :
class Role extends Model
{
protected $table='company_role';
protected $fillable = [
'sl', 'name', 'parent_id'
];
}
Now I want to fetch all the companies of related project and sort them out with sl of role, for this I am trying to do a join something like this:
$companies = Project\AssociateCompany::whereHas('project', function ($q) use($request) {
$q->where('slug', $request->slug);
})
->with('companyRole')
->join('company_role', 'project_associate_company.id', '=', 'company_role.project_associate_company_id')
->orderBy('company_role.sl', 'desc')
->paginate(20);
So in this I am getting an error:
SQLSTATE[42S22]: Column not found: 1054 Unknown column 'company_role.project_associate_company_id' in 'on clause' (SQL: select count(*) as aggregate from project_associate_company inner join company_role on project_associate_company.id = company_role.project_associate_company_id where exists (select * from projects where project_associate_company.project_id = projects.id and slug = kovacek-rodriguez and projects.deleted_at is null) and project_associate_company.deleted_at is null)
Help me out in this.
I want to search in contacts table and in communication links table according to name or mobile no. where my mobile is in communication_links table in 'value' and fname and lname is in contacts table. but there is a relation in communication link and in resource_status by using rest_id. and again resource_status is connected with resource type.
This is my raw sql query
SELECT contacts.fname, contacts.lname, communication_links.value FROM contacts ,communication_links,resource_status
where
(contacts.id = communication_links.cont_id)
AND
(communication_links.rest_id = resource_status.id)
AND
resource_type.status LIKE '{mobile}%'
AND
(communication_links.value LIKE '{$search_string}%' OR
contacts.fname LIKE '{$search_string}% OR contacts.lname LIKE '{$search_string}% )
I have following table structure
contacts
id
fname
lname
dob
communication_links
id
rest_id
cont_id
value
resource_type
id
type
resource_status
id
Status
rety_id
And I created following models to maintain the relationship
Contact.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Contact extends Model
{
protected $connection = 'mysql_freesubs';
public $timestamps = false;
public function communicationLinks()
{
return $this->hasMany(Communication_link::class, 'cont_id');
}
}
Communication_link.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Communication_link extends Model
{
protected $connection = 'mysql_freesubs';
public $timestamps = false;
public function resource()
{
return $this->belongsTo(Resource_status::class, 'rest_id');
}
public function contact()
{
return $this->belongsTo(Contact::class, 'cont_id');
}
}
Resource_status.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Resource_status extends Model
{
protected $connection = 'mysql_freesubs';
protected $table = 'resource_status';
}
Resource_type.php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Resource_type extends Model
{
protected $connection = 'mysql_freesubs';
public $timestamps = false;
public function resourceStatuses()
{
return $this->hasMany(Resource_status::class, 'rety_id');
}
}
I tried to write same query as i have given above but i haven't got a desire result:
$parent_contact = \App\Contact::with('communicationLinks.resource')
->whereHas('communicationLinks.resource', function ($query) {
$query->where('status', 'LIKE', "{mobile}%");
})
->whereHas('communicationLinks.contact',function ($query) use($request) {
$query->where('communicationLinks.value','LIKE',"{$request->search_string}%")
->orWhere('fname','LIKE',"{$request->search_string}%")
->orWhere('lname','LIKE',"{$request->search_string}%");
})
->get();
$query = DB::table("contacts as a")
->select(array("a.fname", "b.lname", "b.value"))
->join("communication_links AS b", "a.id", "=", "b.cont_id")
->join("resource_type AS c", "b.rest_id", "=", "c.id")
->where("a.status", "like", $mobile."%")
->where("b.value", "like", $search_string."%")
->orWhere("a.fname", "like", $search_string."%")
->orWhere("a.lname", "like", $search_string."%")
->get();
That should do the job for you.
You can just iterate through it to get your values as desired
I'm using Laravel 4. I have the following models:
class User extends Eloquent {
protected $table = 'users';
public function questions()
{
return $this->hasMany('UserQuestion', 'user_id', 'user_id');
}
}
class UserQuestion extends Eloquent {
protected $table = 'user_questions';
public function user()
{
return $this->belongsTo('User', 'user_id', 'user_id');
}
public function subquestions()
{
return $this->hasMany('UserSubquestion', 'question_id', 'id');
}
}
class UserSubquestion extends Eloquent {
protected $table = 'user_subquestions';
public function question()
{
return $this->belongsTo('UserQuestion', 'question_id');
}
public function answers()
{
return $this->hasMany('UserAnswer', 'subquestion_id', 'id');
}
}
class UserAnswer extends Eloquent {
protected $table = 'user_answers';
public function subquestion()
{
return $this->belongsTo('UserSubquestion', 'subquestion_id');
}
}
I have the following query:
$results = User::with(['questions' => function($query) {
$query->where('status', '1');
$query->where('category', 'medicine');
}])
->with('questions.subquestions', 'questions.subquestions.answers')
->get();
However, the where conditions I'm applying to the questions relationship aren't being applied to the joined tables (subquestions and answers).
How can I make the conditions apply to them as well?
Note: The values of status and category in the conditions are dynamic (i.e. won't always be 1 or medicine).
Try doing your call like this instead:
$results = User::with(['questions' => function($query) {
$query->where('status', '1');
$query->where('category', 'medicine');
},
'questions.subquestions',
'questions.subquestions.answers'
])->get();
Note, this time the method with is only called once.
I have 4 tables:
conversations
- id (pk)
- userId1 (fk)
- userId2 (fk)
users
- id (pk)
- name
- surname
.
.
.
- roleId (fk)
- userStatusId (fk)
roles
- id (pk)
- type (fk)
user_status
- id (pk)
- description (fk)
this are my models:
class Conversation extends Eloquent {
public function user1(){
return $this->hasOne('User', 'id', 'userId1');
}
public function user2(){
return $this->hasOne('User', 'id', 'userId2');
}
}
class User extends Eloquent {
public function role(){
return $this->hasOne('Role', 'id', 'roleId');
}
public function userStatus(){
return $this->hasOne('UserStatus', 'id', 'userStatusId');
}
// public function conversation1(){
// return $this->belongsToMany('Conversation', 'id', 'userId1');
// }
// public function conversation2(){
// return $this->belongsToMany('Conversation', 'id', 'userId2');
// }
}
class UserStatus extends Eloquent {
public $timestamps = false;
protected $table = 'user_status';
public function user(){
return $this->belongsToMany('User', 'id', 'userStatusId');
}
}
class Role extends Eloquent {
public $timestamps = false;
public function user(){
return $this->belongsToMany('User', 'id', 'roleId');
}
}
Now what I want to do is, for example, take all the conversations where the "userId1" (on conversations) is of a "user" who have the status "description" equal to "registered".
That's what I do:
Route::get('/', function(){
$conversation = Conversation::with(array('user1.userStatus' => function ($query){
$query->where('description', '=', 'registered');
}))->get();
foreach ($conversation as $conv) {
echo '<br \>';
echo $conv;
}
});
I expect to receive all the conversations record where the status of the userId1 is "registered" and nothing else... Instead what I receive are all the conversations records and, for each one, the user records and the records of the userStatus table (of this last I receive just the one who match the where clause and the ones who are not have a null value).
I know my english is terrible but I hope someone could understand and help me. Thanks!
All your relations are wrong. You need to read http://laravel.com/docs/eloquent#relationships and in your case it's:
class Conversation extends Eloquent {
public function user1(){
return $this->belongsTo('User', 'userId1');
}
public function user2(){
return $this->belongsTo('User', 'userId2');
}
}
class User extends Eloquent {
public function role(){
return $this->belongsTo('Role', 'roleId');
}
public function userStatus(){
return $this->belongsTo('UserStatus', 'userStatusId');
}
}
class UserStatus extends Eloquent {
public $timestamps = false;
protected $table = 'user_status';
public function user(){
return $this->hasMany('User', 'userStatusId');
}
}
class Role extends Eloquent {
public $timestamps = false;
public function user(){
return $this->hasMany('User', 'roleId');
}
}
Now, to retrieve only those conversations you want this:
Conversation::whereHas('user1', function ($q) {
$q->whereHas('userStatus', function ($q) {
$q->where('description', 'registered');
});
})->get();
or using this PR https://github.com/laravel/framework/pull/4954
Conversation::whereHas('user1.userStatus', function ($q) {
$q->where('description', 'registered');
})->get();
Also, to make it more verbose, you can wrap that code in a scope:
// User model
public function scopeRegistered($query)
{
$q->whereHas('userStatus', function ($q) {
$q->where('description', 'registered');
});
}
then:
Conversation::whereHas('user1', function ($q) {
$q->registered();
})->get();
You may try this:
$conversations = Conversation::whereHas('user1.userStatus', function ($query){
$query->where('description', '=', 'registered');
})->get();
This will return only the Conversation models whose related user1.userStatus is registered.
Models
class WPModel extends Eloquent
{
protected $table = 'work_processes';
protected $guarded = array('id');
protected $softDelete = true;
// declaring one-to-many relationship
public function relatedWPAQs()
{
return $this->hasMany('WPAQModel', 'wp_id');
}
public function relatedUsers()
{
return $this->belongsTo('UserModel', 'wp_owner_id');
}
}
class UserModel extends Eloquent
{
protected $table = 'users';
protected $softDelete = true;
public function relatedWPs()
{
return $this->hasMany('WPModel', 'wp_owner_id');
}
}
class WPAQModel extends Eloquent
{
protected $table = 'wp_audit_questions';
protected $fillable = array('wp_id', 'wp_audit_question');
// declaring one-to-many relationship - the inverse way
public function relatedWP()
{
return $this->belongsTo('WPModel', 'wp_id');
}
public function scopeWpParent($query, $id)
{
return $query->where('wp_id', '=' ,$id);
}
}
Controller
class WPAQController extends BaseController
{
public function showWPAQ($wpid)
{
$workprocess = WPModel::where('id', $wpid)
->join('users', 'users.id', '=', 'work_processes.wp_owner_id')
->select('users.user_name', 'work_processes.*')
->with(array(
'relatedWPAQs' => function($query) use ($wpid)
{
$query->where('wp_id', '=',$wpid);
}
))
->get();
return View::make('wpaqshow')->with(compact('workprocess'));
}
}
when I run this code, I get following error
SQLSTATE[23000]: Integrity constraint violation: 1052 Column 'id' in
where clause is ambiguous (SQL: select users.user_name,
work_processes.* from work_processes inner join users on
users.id = work_processes.wp_owner_id where
work_processes.deleted_at is null and id = ?) (Bindings: array (
0 => '1', ))
Try the following:
$workprocess = WPModel::where('work_processes.id', $wpid)
->join('users', 'users.id', '=', 'work_processes.wp_owner_id')
->select('users.user_name', 'work_processes.*')
->with(array(
'relatedWPAQs' => function($query) use ($wpid)
{
$query->where('wp_id', '=',$wpid);
}
))
->get();
You have joined few tables. Now laravel has many Ids. You have to tell Laravel which id in where clause Laravel should use..
WPModel::where('id', $wpid)