I want to use where clause on the another relationship not my current selecting model as below table
table Customer
-------id-----customer_name
Table ModelA
table Customer
-------id-----fk_custome_id
table ModelB
-------id-----fk_ModelA_id
Function in Controller
$data['data'] = customer::with(['modelA','modelA.modelB'])
->where('fk_customer_id', 2)->get();
Customer Model
final function ModalA (){
return $this->hasMany('App\Models\ModelA', 'fk_customer_id', 'id');
}
ModelA Model
final function Modelb (){
return $this->hasMany('App\Models\ModelB', 'fk_modelA_id', 'id');
}
Error:
I will got error as below because select sql don't find the column name fk_customer_id in table customer, So how can I user fk_customer_id (in table ModelA) for where.
You can useYou can use whereHas like:
$data['data'] = customer::with(['modelA','modelA.modelB'])
->whereHas('modelA', function ($query) {
$query->where('fk_customer_id', 2);
})->get();
It's because when you're using with you just eager load constrints but you won't attach it to the main query (of the customer model). So there are two way: one modern with using whereHas or using join queries.
Related
I have an orders table, an items table, and a pivot table called item_order which has two custom fields (price, quantity). The relationship between Order and Item is belongsToMany. I'm trying to return the count of all items with an id of 1, where the parent Order->status == 'received'. For the life of me, I can't figure out how to do this.
class Order extends Model
{
public function items()
{
return $this->belongsToMany(Item::class)->withPivot('price', 'quantity');
}
}
class Item extends Model
{
public function orders()
{
return $this->belongsToMany(Order::class)->withPivot('price', 'quantity');
}
}
Try this:
$total_quantity = Item::find(1) // getting the Item
->orders() // entering the relationship
->with('items') // eager loading related data
->where('status', '=', 'received') // constraining the relationship
->get() // getting the results: Collection of Order
->sum('pivot.quantity'); // sum the pivot field to return a single value.
The strategy here is to find the desired Item to then get the related Orders to this Item that has a 'received' status, to finally sum the pivot attribute in order to get a single value.
It should work.
Considering you know the id of the item, most performant way would be to query item_order table directly. I would create a pivot model for ItemOrder and define the belongsTo(Order::class) relationship and do this:
$sum = ItemOrder::where('item_id', $someItemId)
->whereHas('order', function ($q) {
return $q->where('status', 'received');
})
->sum('quantity');
i'm trying to get all the lead_id inside my pivot table but i can't make it work.
controller:
$levels = Level::all();
$levels->lead()->attach('lead_id');
return $levels;
Model Level:
public function lead(){
return $this->belongsToMany(Lead::class, 'level_students')->withPivot('level_id', 'lead_id');
}
Model Lead:
public function level(){
return $this->belongsToMany(Level::class, 'level_students')->withPivot( 'lead_id', 'level_id');
}
If you mean all lead_id of a Level, then you can use pluck().
$level->lead->pluck('lead_id');
I'm not really sure what you are trying to achieve because it seems that you want to retrieve all lead_id associated with any Level. But if that is the case, then you can create a model for the pivot table (e.g. LevelLead) and use distinct() or with Query Builder:
$leadIds = DB::table('level_students')->select('lead_id')->distinct()->get();
If you want to get the referenced table's column (e.g. leads table's name column) then you can use JOIN. Check Laravel's doc for more options. For example, assuming the table name for Lead is leads, then:
$leads = DB::table('level_students')->join('leads', 'level_students.lead_id', '=', 'leads.lead_id')->select('level_students.lead_id', 'leads.name')->distinct()->get();
I have four tables
**Articles table**
id
title
body
owner_id
category_id
**Favorite articles table**
id
user_id
article_id
**User table**
id
user_name
user_type
**Category table**
id
category_name
How to get list of favorite articles (article_name,owner_name,category_name) which related to currently logged user from db using laravel eloquent?
Is it possible to do it in single line request? e.g.:
$articles_data=Auth::user()->favorite_articles->article...
EDIT
For the moment i have to use statement below:
$articles_data = FavoriteArticle::where('user_id', Auth::id())->join('articles', 'articles.id', '=', 'favorite_articles.article.id')
->join('users', 'users.id', '=', 'favorite_articles.user_id')
->join('categories', 'categories.id', '=', 'articles.id')
->get()
Which looks a bit complicated and doesn't use eloquent relations.
Completing #zippo_ answer, in the Controller you must reference what tables you want, e.g.
User.php
use Article;
public function article()
{
return $this->hasOne('App\Article');
}
and in the e.g. UserController.php
$user = User::with('article')->get();
EDIT:
if you want to relate User to Article.Category, after create a relation with user and article
Article.php
use Category;
public function category()
{
return $this->hasOne('App\Category');
}
e.g. UserController.php
$user_articles_categories = User::with('article.category')->get();
You can take advantage of laravel eager loading, which are also called as Eloquent relationships.
Eloquent relationships are defined as functions on your Eloquent model classes.
Eg. In Article Model
public function article()
{
return $this->hasOne('App\Model\Category');
}
In this way, you need to define all the relationships in the respective Model classes.
for more info: http://laravel.com/docs/5.1/eloquent-relationships
I have a table Registrationrequests where I have course_id and user_id and some other field.
$users_id = Registrationrequest::where('course_id', $query_course_user)->where('registered', 1)->get();
From the above query it gives me an array of result. But I need to take the details of these user_id from another table Users. I'm using Laravel. Table models are Registrationrequest and User
How can I get the user details from the above select result? I'm not that good in Joins. Any advice?
Use Eloquent's whereHas method:
$courseId = Request::get('course_id');
$users = User::whereHas('registrationRequests', function($query) use ($courseId)
{
$query->where('course_id', $courseId)->where('registered', 1);
});
This assumes you have set up the proper relationship in your User model. If not, add this method to your user model:
public function registrationRequests()
{
return $this->hasMany('Registrationrequest');
}
Want to get selected columns, when querying through pivot table. Following is my scenario.
I have 3 tables,
coupons
coupon_cities
cities
relationship details are as following.
class Coupon extends Eloquent {
public function cities(){
return $this->belongsToMany('City', 'coupon_cities', 'coupon_id', 'city_id');
}
}
When I query
Coupon::with('cities')
it returns array of all columns of city table for each entry of coupon row
The only way is this:
$coupon = Coupon->first();
$coupon->cities()->get([your columns here]);
Normally you'd do it like below:
Coupon::with(['cities' => function ($q)
{
$q->select('column', 'column2' ...);
}
However it won't work for belongsToMany relation -> https://github.com/laravel/framework/pull/4440