Treeview with Laravel and Database - laravel

I found this function in Internet and it works.
In my App
public function childs(){
return $this->hasMany('App\Account','p_id');
}
In my route:
Route::get('tests', function(){
return App\Account::with('childs')
->where('p_id',0)
->get();
});
So if you have in the dabase a raw with p_id = 0 and id = 1 it return a category and if you have a raw with p_id = 1 and id = 2 that mean that the child of the categorie with id = 1.
Another example::
If you have a raw with p_id = 6 and id = 16 that mean that the child of the category with id = 6
Please who can explain to mean why exactly it work like that ?

Laravel Relationship are not used to make relations between 1 model. You cannot make relation between Account and Account. An account does not has "hasMany" accounts.
You can have hasMany users for example.
public function childs(){
return $this->hasMany('App\User','p_id');
}

Related

Get only one column from relation

I have found this: Get Specific Columns Using “With()” Function in Laravel Eloquent
but nothing from there did not help.
I have users table, columns: id , name , supplier_id. Table suppliers with columns: id, name.
When I call relation from Model or use eager constraints, relation is empty. When I comment(remove) constraint select(['id']) - results are present, but with all users fields.
$query = Supplier::with(['test_staff_id_only' => function ($query) {
//$query->where('id',8); // works only for testing https://laravel.com/docs/6.x/eloquent-relationships#constraining-eager-loads
// option 1
$query->select(['id']); // not working , no results in // "test_staff_id_only": []
// option 2
//$query->raw('select id from users'); // results with all fields from users table
}])->first();
return $query;
In Supplier model:
public function test_staff_id_only(){
return $this->hasMany(User::class,'supplier_id','id')
//option 3 - if enabled, no results in this relation
->select(['id']);// also tried: ->selectRaw('users.id as uid from users') and ->select('users.id')
}
How can I select only id from users?
in you relation remove select(['id'])
public function test_staff_id_only(){
return $this->hasMany(User::class,'supplier_id','id');
}
now in your code:
$query = Supplier::with(['test_staff_id_only:id,supplier_id'])->first();
There's a pretty simple answer actually. Define your relationship as:
public function users(){
return $this->hasMany(User::class, 'supplier_id', 'id');
}
Now, if you call Supplier::with('users')->get(), you'll get a list of all suppliers with their users, which is close, but a bit bloated. To limit the columns returned in the relationship, use the : modifier:
$suppliersWithUserIds = Supplier::with('users:id')->get();
Now, you will have a list of Supplier models, and each $supplier->users value will only contain the ID.

Defining relations on same table Laravel 5.3

I have a refferal system in my application.ie, One user can reffer other.
Users table
id name
1 A
2 B
3 C
Referrals table
id referrer_id referee_id
1 1 2
2 2 3
I want to show the referrals made by a user.
User Model
public function referrals()
{
return $this->hasMany('App\Models\Referral','referee_id','id');
}
Referral Model
public function referrer_user()
{
return $this->belongsTo('Modules\User\Models\User','referrer_id','id');
}
public function referee_user()
{
return $this->belongsTo('Modules\User\Models\User','referee_id','id');
}
Defining hasMany relationship in User model and belongsTo relationship in Referrals Model, I'am not getting the desired result.
#foreach($user->referrals as $key => $referral)
{{dd($referral->referee_user->name)}}
#endforeach
This returning me the name of user itself(referrer) not the referee
You are referring the ManyToMany relationship the wrong way.
Anyways, it'll be much easier and efficient the following way.
id name referred_by
1 abc null
2 def 1
3 gfd 2
User Model
/**
* Who did he bring onboard?
*/
public function referrals(){
return $this->hasMany('....User', 'referred_by');
}
//Who brought him onboard..
public function referree(){
return $this->belongsTo('...User', 'referred_by');
}
Just check out the appropriate syntax.

Laravel eloquent use id from one table to search junction table?

So I have 3 tables
-Business
- id
-Address
- id
-business_address
- business_id
- address_id
And now at the moment when I go into a view business page I pass business->id from business table as $id:
public function displayBusiness($id) {
$business = Business::find($id);
$address = Address::find($id);
Which works absolutely fine at this moment but what if address has a different id?
so:
-Business
- id = 1
-Address
- id = 2
-business_address
- business_id = 1
- address_id = 2
So how can I modify that so that when id in business table = 1 it goes into business_address and find matching address id and bring back records that match it
What you should have is a relationship. So in your Business model you'd add the following.
public function addresses() {
return $this->belongsToMany(Address::class, 'business_address', 'address_id', 'business_id');
}
Then in your Address model you'd have the following.
public function addresses() {
return $this->belongsToMany(Business::class, 'business_address', 'business_id', 'address_id');
}
With this, you can now do the following.
public function displayBusiness($id) {
$business = Business::with('addresses')->find($id);
}
Then you access addresses by doing $business->addresses.
This is all based on what you currently have, so I'm assuming that one Address can belong to several Business. If this should not be the case, you'll need to refactor your relationship and database, as the pivot table isn't needed.

How to do complicated query SQL in Laravel?

I use three entities: user, categories, user_categories, articles, articeles_category
Each user can be subscribe on some categories, so table user_categories will be:
user_category
id user_id category_id
1 1 1
articles_category
id article_id category_id
1 1 1
articles
id name
1 Bla
So, I need to select all articles where articeles_category that correspond to the categories on user subsribed in table user_categories.
I tried this:
Articles::with("categories")->with("publisher.categories")->where("user_id", 1);
public function categories()
{
return $this->hasMany("App\ArticlesCategory", "article_id", "id");
}
public function publisher()
{
return $this->hasOne("App\User", "id", "user_id");
}
I have some ideas.
At first join tables:
user_categories with articeles_category by conditions:
user_categories.category_id = articeles_category.id AND user_categories.user_id = 4
Second is:
Select articles from Articles join with previous query.
Third is
To make global where by user_id
If your models are linked from users to categories to articles, you can do:
$categories = $user->categories()->with('articles')->get();
Then group them under the same collection (if you want):
$articles = $categories->map(function($category){
return $category->articles;
});
Alternatively, if you do not have the user instance:
$user = User::find($user_id)->with('categories.articles').->get();
See eager loading: https://laravel.com/docs/5.4/eloquent-relationships#eager-loading

Laravel Eloquent Joins use of belongs to

I have 2 table for get inner join query records in laravel eloquent, but is not working with combine data get.
Table :category
id
name
cat_status
Table:image
id
title
desc
img_status
image controller
//get all active images
ImageModel::where('status',true)->get();
public function getCategory() {
return $this->belongsTo('\App\Api\CategoryModel','cat_id');
get category active only
public function getActiveCategory() {
return $this->getCategory()->where('cat_status','=', 1);
}
I need to get only which category is active, that images only.
if cat 1,2,3 3(is inactive)
image table
title=a1,cat_id=1,
title=a2,cat_id=2,
title=a3,cat_id=3
Now I get all 3 images , i need only first 2, because cat_id 3 is inactive .
Any ideas how I can join the status condition.
Thanks in advance.
Well relation methods doesn't provides joins. You have to do it manually.
If You want to get IMAGES from active categories then You''ll have to query like this:
// method from image model
public function getImagesFromActiveCategory() {
return $this->join('category')
->select('image.*')
->join('category', 'category.id', '=', 'image.cat_id')
->where('cat_status','=', 1)
->get();
}
Thank you for your giving the quick responses,
I tried to use other but is solved now with the use of belongsToMany Method.
Below functions gives exact records from the DB, which match with each category and images table, and category status active records only.
#Image Controller
$images= ImageModel::where('status',true)->get();
foreach($images as $img){
#get data
$onlyactiveCategoryImages=$img->getActiveCategory()->get();
}
#image Model
#get category data
public function getCategory() {
return $this->belongsToMany('\App\Api\CategoryModel','images','id','cat_id');
}
#get category active only
public function getActiveCategory() {
return $this->getCategory()->where('cat_status','=', 1);
}
Thank you once again for all :).

Resources