Issue in laravel 5.3 relationship? - laravel

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

Related

Laravel filtering query results with relations

I have this relations
and defined models for all 3 tables
class Employee extends Model
{
use HasFactory;
protected $table = 'employees';
public function departments()
{
return $this->belongsToMany(Department::class, 'dept_emp', 'emp_no', 'dept_no', 'emp_no', 'dept_no');
}
}
class Department extends Model
{
use HasFactory;
protected $table = 'departments';
}
class Dept_emp extends Model
{
use HasFactory;
protected $table = 'dept_emp';
}
And in my controller
$employees = Employee::with('departments')->paginate(50);
I want to filter this query result to be able to select only one chosen department and not all of them.
I tried adding to employee model this function
public function scopeDepartment($query, $department)
{
return $query->where('dept_no',$department);
}
but it isn't working. Can someone advice me how to filter query results with relations?
you can query within with relation as like
$employees = Employee::with(['departments' => function($q) use ($dept_id){
$q->where('dept_no',$dept_id);
}])->paginate(50);
$dept_id is the id of department i.e $dept_id = $request->department_id something like

Laravel relationship many to many filtering on pivot field

I have a relationship between Invoice and Shift.
Invoice model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Invoice extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'user_id',
'date_ins',
'closeco',
'closedrh',
'lvl',
'new',
];
public function user()
{
return $this->hasOne(User::class,'id','user_id');
}
/**
* The roles that belong to the invoice.
*/
public function shifts()
{
return $this->belongsToMany(Shift::class, 'invoice_shift')
->withPivot([
'invoice_id', 'shift_id', 'shift_taken_id', 'shift_swapped_date', 'shift_taken_date', 'tas',
'status_tas', 'status_co', 'status_drh', 'back_co',
'msg', 'msg_co', 'msg_drh'
])
->orderBy('status_drh', 'ASC')
->orderBy('status_co', 'ASC');
}
}
Shift model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Shift extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'code',
'description',
];
/**
* The users that belong to the role.
*/
public function invoices()
{
return $this->belongsToMany(Invoice::class, 'invoice_shift')
->orderBy('status_drh', 'ASC')
->orderBy('status_co', 'ASC');
}
}
So I have a pivot table called Invoice_shift.
I cannot extract, starting from invoices table, just invoices that have tas (in invoice_shift table) = current logged user.
I cannot filter as a static value in Invoice model definition with wherepivot because it is dynamic value, every time logged user id is different.
I tried to do this in controller
$invoices = Invoice::with('shifts.invoices')
->orderBy('date_ins', 'DESC')->get();
$filter = $invoices->shifts()
->wherePivot('tas', '=', $user_id)
->get();
but I get an error because I think invoices are a collection ... I tried to insert a foreach...but it doesn't work.
The error message:
Method Illuminate\Database\Eloquent\Collection::shifts does not exist
How can I do this?
Thanks
$invoices is an instance of Illuminate\Database\Eloquent\Collection and therefore relationship shifts() cannot be used..
Maybe you need the correct Eloquent builder to filter invoices using whereHas("relationship", fn)
$filteredInvoices = Invoice::with('shifts.invoices')
->whereHas("shifts", function($query) use ($user_id) {
$query->wherePivot('tas', $user_id)
})
->orderBy('date_ins', 'DESC')
->get();

laravel filter on relationship

hi i have this relationships with these 3 models
Customers
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Customers extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'contr_nom',
'contr_cog',
'benef_nom',
'benef_cog',
'email',
'polizza',
'targa',
'iban',
'int_iban',
'cliente',
];
public function claims()
{
return $this->hasMany(Claims::class);
}
public function refunds()
{
return $this->hasManyThrough(Refunds::class, Claims::class);
}
}
Claims
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Claims extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'dossier',
'date_cla',
];
public function refunds()
{
return $this->hasMany(Refunds::class);
}
public function customers()
{
return $this->belongsTo(Customers::class,'customers_id');
}
}
and Refunds
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Refunds extends Model
{
public $primaryKey = 'id';
protected $fillable = [
'date_ref',
'status_ref',
'disactive',
];
public function services()
{
return $this->belongsToMany(Services::class)
->withPivot(['services_id','services_amount','services_status']);
}
public function claims()
{
return $this->belongsTo(Claims::class,'claims_id');
}
}
i have this in the controller (part of the code)
$data = Claims::with(array('customers'=>function($query){
$query->select('id','contr_nom','contr_cog','targa','email','gcliente');
}))->get();
it works, i can get customers information (parent table) for each dossier ( i put in a datatables)
But i cannot insert another filter based on Refunds table.
I need to show only dossiers where
['status_ref', '>',4]
the problem is that status_ref is in Refunds table
i tried to do somthing like this but no works
$data = Claims::with(array('customers'=>function($query){
$query->select('id','contr_nom','contr_cog','targa','email','gcliente');
}))->refunds()
->where('status_ref', '>',4)
->get();
I cannot understand why....
Thx
You have to use whereHas like:
$data = Claims::with(array('customers'=>function($query){
$query->select('id','contr_nom','contr_cog','targa','email','gcliente');
}))
->whereHas('refunds', function (Builder $query) {
$query->where('status_ref', '>', 4);
})
->get();

how to make join query between three tables in laravel

I want to build a query in laravel between three tables (regions, countries, packages) such that table are related together.
regions table contains (id, name, description)
countries table contains (id, region_id, name, description)
packages table contains (id, county_id, pkg_title, pkg_description, price)
I want to select all packages where region_id=1
how can I make query for this situation in laravel query builder. please help me about this question
Set your models as follows.
class Region extends Model
{
}
class Country extends Model
{
public function region()
{
return $this->belongsTo(Region::class);
}
}
class Package extends Model
{
public function country()
{
return $this->belongsTo(Country::class);
}
}
And state following query inside your method.
$region_id = 1;
$PackageWithRegions = Package::with([
'country' => function ($county) use ($region_id) {
return $county->with([
'region' => function ($region) use ($region_id) {
return $region->where('id', $region_id);
}
]);
}
])->get();
// $PackageWithRegions is a collection of packeges with regions where regiion_id = 1
More on eloquent relationships
You can use Eloquent model relationship to prform this, like below
In region controller file
$region = Region::where(['id'=>1])->with(['country'])->get(); ///fetch region with country calls relation declared in region model
In Region.php model
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Region extends Model {
protected $table = 'regions';
public function country(){
return $this->hasOne('App\Models\Country','region_id')->with(['packages']); ///this will fetch country with all pacckages on matching region_id, join of package with country is declared in country model.
}
}
In Country.php model
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Country extends Model {
protected $table = 'countries';
public function packages(){
return $this->hasMany('App\Models\Package','county_id'); //join of country with packages on county_id
}
}
In Package.php model
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Package extends Model {
protected $table = 'packages';
}
You can see in Laravel doc (https://laravel.com/docs/4.2/eloquent) in section Has Many Through that if you have a model like:
countries
id - integer
name - string
users
id - integer
country_id - integer
name - string
posts
id - integer
user_id - integer
title - string
Then you can access to last relation in this way:
class Country extends Eloquent {
public function posts()
{
return $this->hasManyThrough('Post', 'User');
}
}
Or using customs relations IDs:
class Country extends Eloquent {
public function posts()
{
return $this->hasManyThrough('Post', 'User', 'country_id', 'user_id');
}
}
So, you can access to the posts of a country:
$posts = Country::get(2)->posts;
// with where:
$posts = Country::where('name', '=', 'USA')->get()->posts;

How to paginate objects from a relationship

How can i return this same query with pagination from the relacted produtos with categoria?
My Model DB:
Config Model Eloquent categoria:
namespace App\Models;
class Categoria extends ModelDefault
{
protected $table = 'categoria';
public function produtos()
{
return $this->belongsToMany('App\Models\Produto', 'categoria_produto', 'categoria_id')->withTimestamps();
}
}
Config Model Eloquent produto:
namespace App\Models;
class Produto extends ModelDefault
{
protected $table = 'produto';
public function categorias()
{
return $this->belongsToMany('App\Models\Categoria', 'categoria_produto', 'produto_id')->withTimestamps();
}
public function images()
{
return $this->hasMany('App\Models\ProdutoImagem','produto_id', 'id');
}
}
My query to get produtos from categoria:
$produtosPorCategoria = Categoria::with(['produtos.images.image'])
->where('slug', $categoria_slug)
->ativo()
->first();
dd($produtosPorCategoria);
Here you can see a printscreen from my returned array:
If I understood what you need. you should try this
$produtosPorCategoria = Categoria::with(['produtos.images.image'])
->where('slug', $categoria_slug)
->ativo()
->first();
Should be
$produtosPorCategoria = Categoria::with(['produtos.images.image'])
->where('slug', $categoria_slug)
->ativo()
->first();
$produtosPorCategoria = $produtosPorCategoria->produtos()->paginate(5);

Resources