I have 3 tables this table is related to, I will call this table with
belanja (parent)
anak_belanja (child)
supplier (has relation with parent)
I can create this relation from parent and child but on table supplier I get an error. Usually I use "with" and I get no error, but now I use query builder and I have a problem
My Belanja Model
public function supplier()
{
return $this->belongsTo(\App\Models\Suplier::class ,'supplier_id');
}
My Anak_Belanja model
public function belanja()
{
return $this->belongsTo(\App\Models\Belanja::class ,'belanja_id');
}
and this is my controller
public function render()
{
$user_id = Auth::user()->id;
$sub = SubRincianUraianKegiatan::where('user_id', $user_id)
->where('id' , $this->newid)
->pluck('uraian', 'id');
$sup = Supplier::all()->pluck('nama' ,'id');
$data = DB::table('belanja AS t')
->select([
't.id',
't.uraian',
't.tgl_belanja',
't.supplier_id',
DB::raw('coalesce(sum(p.harga * p.qty),0) AS total_order')
])
->leftjoin('suplier AS s','t.suplier_id','=','s.id') // on here i think this error
->leftjoin('anak_belanja AS p','p.belanja_id','=','t.id')
->where('sub_id', $this->newid)
->where('uraian', 'like', '%'.$this->search.'%')
->groupBy('t.id')
->groupBy('t.uraian')
->groupBy('t.tgl_belanja')
->groupBy('t.suplier_id')
->paginate(10);
return view('livewire.detail-belanja-lw',
['data' => $data ,
'sup' => $sup,
'sub' => $sub,
]);
}
In my blade I try to add supplier like that
{{$i->supplier->nama}}
but I get an error
Undefined property: stdClass::$supplier
Can someone explain my mistake?
$data = DB::table('belanja AS t')
->select([
't.id',
't.uraian',
't.tgl_belanja',
't.suplier_id',
DB::raw('coalesce(sum(p.harga * p.qty),0) AS total_order'),
DB::raw('s.nama as nama')
])
->leftjoin('suplier AS s','t.suplier_id','=','s.id') // on here i think this error
->leftjoin('anak_belanja AS p','p.belanja_id','=','t.id')
->where('sub_id', $this->newid)
->where('uraian', 'like', '%'.$this->search.'%')
->groupBy('t.id')
->groupBy('t.uraian')
->groupBy('t.tgl_belanja')
->groupBy('t.suplier_id')
->paginate(10);
try this.
Related
I want to get category with all children subcategories and posts where id = category_id.
Posts should be paginated.
In category model I have 2 relations.
public function children() {
return $this->hasMany(self::class, 'parent_id');
}
public function posts() {
return $this->hasMany(Post::class, 'category_id');
}
In controller I have this function
public function getCategoryWithPaginatedPosts($slug, $perPage = null)
{
$columns = ['id', 'parent_id', 'title', 'slug', 'description', 'image'];
$postsColumns = ['category_id','title','text'];
$result = Category::whereSlug($slug)
->select($columns)
->with('children')
->with(['items' => function ($q) use ($postColumns) {
$q->wherePublished(true)
->select($postColumns)
->orderBy('id', 'ASC')
->paginate();
}])
->first();
}
Pagination doesn't work.
I just see that number of items is equal to $perPage parameter (and I have more items), but I don't see paginator inside dd($result->items)
It works like that, though I believe it is not the best way to do that.
So I can do it in few steps.
In first step I retrieve all data from DB and convert models to array, because I don't need models on webpage and I suppose it works faster like that. I would use ->toBase() if it could take mutators and relations from the model.
Second step I convert array into stdClass, because it is more comfortable in blade to work with object rather than with array.
Third step is to paginate items with mypaginate function (manual paginator in AppService Provider).
public function getCategoryWithPaginatedPosts($slug, $perPage = null)
{
$columns = ['id', 'parent_id', 'title', 'slug', 'description', 'image'];
$postsColumns = ['category_id','title','text'];
$result = Category::whereSlug($slug)
->select($columns)
->with('children')
->with(['items' => function ($q) use ($postColumns) {
$q->wherePublished(true)
->select($postColumns)
->orderBy('id', 'ASC');
}])
->first()
->toArray();
$result = Arr::arrayToObject($result);
$result->items = collect($result->items)->mypaginate($perPage);
return $result;
}
you should not use ->first() after ->paginate(), change something like this,
$result = Category::whereSlug($slug)
->select($columns)
->with('children')
->with(['items' => function ($q) use ($postColumns) {
$q->wherePublished(true)
->select($postColumns)
->orderBy('id', 'ASC')
}])
->paginate(20);
This works but it gives all the fields of account table but only few are required.
$data = Loan::select('*')
->with([
'member' => function ($query) {
$query->addSelect('id', 'name');
},
'member.account'
])
->get();
This gives account: null
$data = Loan::select('*')
->with([
'member' => function ($query) {
$query->addSelect('id', 'name');
},
'member.account'=> function ($query) {
$query->addSelect('id', 'account'); // if this line is commented, all the fields are returned but I just need few fields.
}
])
->get();
Member model:
public function account()
{
return $this->hasOne(Account::class);
}
Account model:
public function member()
{
return $this->belongsTo(Member::class);
}
How can I get only the required fields of account table?
You can define the relationship and set it to give you specific columns like this.
on Member model
public function account()
{
return $this->hasOne(Account::class)->select(['id', 'account']);
}
You can try to define required fields in with:
$data = Loan::select('*')
->with([
'member' => function ($query) {
$query->addSelect('id', 'name');
},
'member.account:id,number'
])
->get();
Your are close you just need to select the foreign key column that points to your account model , I guess it would be account_id, So you basically need to select 3 columns from your table which are select(['id', 'name','account_id'])
$data = Loan::with(['member' => function ($query) {
$query->select(['id', 'name','account_id'])
->with(['account'=> function($query){
$query->select(['id','name']);
}]);
}])
->get();
So if you have another nested relation account -> type and you need specific columns from type so you need to select the foreign key column from accounts models as
with(['account'=> function($query){
$query->select(['id','name','type_id'])
->with(['type'=> function($query){
$query->select(['id','name']);
}]);
}]);
I have three tables: realties, room_types and realty_room_type:
realty_room_type
----------------
id
realty_id
room_type_id
room_type
----------------
id
code
In my Realty model I set a rooms() relationship:
public function rooms()
{
return $this->hasMany(Room::class);
}
I am trying to eager load the rooms() relationship using the with() method. I want to custom what is returned from the relationship, so I am passing a callback function like this:
$realty = Realty::
where('id', $realtyId)
->with([
'rooms' => function ($query) use ($realtyId) {
$query
->leftJoin('room_types', 'room_types.id', '=', 'realty_room_type.room_type_id')
->selectRaw('code, COUNT(*)')
->groupBy('code');
}
])
->get()
);
The problem is I get an empty collection when accessing the relationship using $realty->rooms. Any idea why?
However if I dump and die the statements of the callback function like this:
Realty::
where('id', $realtyId)
->with([
'rooms' => function ($query) use ($realtyId) {
dd($query
->leftJoin('room_types', 'room_types.id', '=', 'realty_room_type.room_type_id')
->selectRaw('code, COUNT(*)')
->groupBy('code'));
}
])
->get()
);
I get what I'd like to be in the rooms() relationship.
Thank you in advance.
You don't need to return inside callback function and call get(). Here you can find the details.
$realty = Realty::
where('id', $realtyId)
->with([
'rooms' => function ($query) use ($realtyId) {
$query
->leftJoin('room_types', 'room_types.id', '=', 'realty_room_type.room_type_id')
->selectRaw('code, COUNT(*)')
->groupBy('code');
}
])
->get();
I can get this to work using a select:
User::whereNotIn('id', $ids)
->select(['id', 'email'])
->with('profile')
->get();
I'd like to only retrieve a couple keys in a user profile that is eagerly loaded. I'd like to do something like this:
User::whereNotIn('id', $ids)
->select(['id', 'email'])
->with(['profile', function ($query) {
$query->select(['id', 'user_id', 'first_name', 'last_name']);
}])->get();
Or:
User::whereNotIn('id', $ids)
->select(['id', 'email'])
->with(['profile', function ($query) {
$query->addSelect(['id', 'user_id', 'first_name', 'last_name']);
}])->get();
But this doesn't seem to work, and I get this error:
ErrorException in Builder.php line 1034:
explode() expects parameter 2 to be string, object given
Thrown in /Illuminate/Database/Eloquent/Builder.php:
/**
* Parse the nested relationships in a relation.
*
* #param string $name
* #param array $results
* #return array
*/
protected function parseNestedWith($name, $results)
{
$progress = [];
// If the relation has already been set on the result array, we will not set it
// again, since that would override any constraints that were already placed
// on the relationships. We will only set the ones that are not specified.
foreach (explode('.', $name) as $segment) { // <--- line 1034
$progress[] = $segment;
if (! isset($results[$last = implode('.', $progress)])) {
$results[$last] = function () {
//
};
}
}
return $results;
}
Is there a way to accomplish this?
Use "addSelect" instead of "select" inside the eager load constraint closure
User::whereNotIn('id', $ids)->select(['id', 'email'])
->with(['profile' => function($query) {
$query->addSelect(['id', 'user_id', 'first_name', 'last_name']);
}])->get();
You have to include the foreign key on the addSelect otherwise nothing will be loaded
I'm writing a code to get nested objects in Laravel. I was wondering if it is possible to write conditions in hasMany or belongsTo.
Here is what I'm doing, that makes the question clear:
$posts = Post::where(
array(
'status' => 'active'
)
)
->orderBy('id', 'asc')
->with(['postResponsibilities' => function($query){
$query->where('status', 'active');
}])
->with(['postRequirements' => function($query){
$query->where('status', 'active');
}])
->with(['postSalaries' => function($query){
$query->where('status', 'active');
}])
->skip($limit * ($page - 1))->take($limit)->get();
So, I have to put nested queries to get only those records whose status is active.
In the Post model, I've written:
public function postRequirements(){
return $this->hasMany('App\Models\PostRequirement', 'post_id');
}
public function postResponsibilities(){
return $this->hasMany('App\Models\PostResponsibility', 'post_id');
}
public function postSalaries(){
return $this->hasMany('App\Models\PostSalary', 'post_id');
}
Is there a way such that I can define status condition inside the nested models?
So that I can write:
$posts = Post::where(
array(
'status' => 'active'
)
)
->orderBy('id', 'asc')
->with('postResponsibilities')
->with('postRequirements')
->with('postSalaries')
->skip($limit * ($page - 1))->take($limit)->get();
I hope the question is clear, thanks
What you can do is apply those conditions inside the relationship methods you put on the Post model, for example:
class Post
{
public function postRequirements() {
return $this->hasMany('App\Models\PostRequirement', 'post_id')
->where('status', 'active');
}
}
Yes it is possible to eager load multiple relationships.
See: https://laravel.com/docs/master/eloquent-relationships#eager-loading
In your case it would be something like:
Post::with('postResponsibilities', 'postRequirements', 'postSalaries')->where()....