Laravel: Querying and accessing child objects in nested relationship with where clauses Many to Many relationship - php

Hi I have a problem to make my laravel query
Model Regions
class Region extends Model
{
protected $table = 'regions';
protected $guarded = [
];
public function county()
{
return $this->belongsTo('App\Models\County');
}
public function companies()
{
return $this->belongsToMany('App\Models\CompanyInfo',
'region_company','region_id','company_id');
}
Model Category
class Category extends Model
{
protected $table = 'categories';
protected $guarded = [];
public function companies()
{
return $this->belongsToMany('App\Models\Company', 'categories_company','category_id','company_id');
}
}
Model Company
class Company extends Model
{
protected $table ='companies';
protected $guarded = [
];
public function regions()
{
return $this->belongsToMany('App\Models\Region', 'region_company','company_id','region_id');
}
}
I have a input form where I want to filter by category and region and the output should be categories with companies if possible but I want to show only 10 companies per category. Not sure it is is possible.
here is what I have till now
$categories = $request->input('categories');
$region = $request->input('regions');
$companies = Category::whereIn('id',$categories)->with([
'companies.regions' => function ($query) use ($region) {
$query->whereIn('id', $region);
}])->get();
the problem here is that it is filtering the categories but it is still giving me all companies not filtering out the once that belong to certain region.
thank you
Dany

Try the following:
$categories = $request->input('categories');
$region = $request->input('regions');
$companies = Category::whereIn('id',$categories)->with([
'companies' => function ($query) use ($region) {
$query->whereHas('region', function ($q2) use ($region){
$q2->whereIn('id', $region);
});
$query->with(['region']);
$query->limit(10);
}])->whereHas('companies', function($q) use ($region) {
$q->whereHas('region', function ($q2) use ($region){
$q2->whereIn('id', $region);
});
})->get();

Related

Laravel 6 - whereHasMorph Relationship Return Empty

I'm new to laravel Polymorphic Relationship. i have 2 table Supplier and Product and have Category to each table, so i'm decide to use Polymorphic Relationship. i want to query supplier-category but its return empty array.
// My Category Model
class Category extends Model
{
protected $fillable = ['categorizable_type', 'categorizable_id'];
public function categorizable()
{
return $this->morphTo();
}
}
// My Supplier Model
class Supplier extends Model
{
protected $fillable = ['name', 'email', 'phone'];
public function categories()
{
return $this->morphMany(\App\Category::class, 'categorizable');
}
}
// My Product Model
class Product extends Model
{
protected $fillable = ['product_code', 'product_name'];
public function categories()
{
return $this->morphMany(\App\Category::class, 'categorizable');
}
}
// And in SupplierController i want to query categorizable_type
public function index(Request $request)
{
// $product = Category::all();
$product = Category::whereHasMorph('categorizable', Supplier::class , function($query){
$query->where('categorizable_type', 'like', '%foo%');
})->get();
dd($product);
// return response()->json($product);
}
Thanks in advance...
Im make it working by change my code like below
$product = Category::whereHasMorph('categorizable', Supplier::class)->get();

Laravel Many to Many relationship gets partial results

I have Course and Category Models with many to many relationship between them. So I created CategoryCourse Model to decompose relationship. Here are my three models:
class CategoryCourse extends Model
{
private $foreignkeys = [
'$category_id','$course_id'
];
public function categories()
{
return $this->belongsToMany('App\Category');
}
public function courses()
{
return $this->belongsToMany('App\Course');
}
}
class Category extends Model
{
protected $title = ['title'];
public function categorycourse()
{
return $this->hasMany('App\CategoryCourse');
}
}
class Course extends Model
{
protected $fillable = [
'title', 'desc'
];
public function categorycourse()
{
return $this->hasMany('App\CategoryCourse');
}
}
In my controller I have method as follows:
public function getCoursesByCategory(Request $request, $id)
{
$id = Hashids::decode($id);
$categories = Category::findOrFail($id[0]);
$courses = $categories->categorycourse()->get();
return view('courses',compact('courses'));
}
I have three tables in database, they are categories, courses and category_courses. My view is displaying results from category_courses but not results from courses. I am learning laravel. Can any one please help? I want to display all courses that belong to a category, in my view.
Here is my view code:
#foreach($courses as $course)
{{$course->title}}
#endforeach
You have to change your code to:
class Category extends Model
{
protected $title = ['title'];
public function courses()
{
return $this->belongsToMany('App\Course', 'category_course', 'category_id', 'course_id');
}
}
The relationship should be in Category only.
And then you call:
$courses = $categories->courses;

Laravel : Select from two tables where column in table two =value using eloquent

I have two tables
table 1 = NewsCollection
table 2 = NewsConllectionTranslation
here is the models
NewsCollection
class NewsCollection extends \Eloquent
{
use \Dimsav\Translatable\Translatable;
public $translatedAttributes = ['title', 'content'];
public $translationModel = 'NewsCollectionTranslation';
public function newsTrans()
{
return $this->hasMany('NewsCollectionTranslation', 'news_collection_id');
}
}
NewsConllectionTranslation
class NewsCollectionTranslation extends \Eloquent
{
public $timestamps = false;
protected $table = 'news_collection_translations';
protected $fillable = ['title', 'content'];
public function transNews()
{
return $this->belongsTo('NewsCollection', 'news_collection_id');
}
}
and here is the show controller
public function show($title)
{
$news = NewsConllectionTranslation::with('newsTrans')->where('title', $title)->first();
return View::make('portal.news.show', compact('news'));
}
What I need to do is
->where('title', $title)->first();
should be selected from NewsConllectionTranslation and I don't want to lose the translation so I don't want to select from NewsConllectionTrnslation first
You should try this:
$news = NewsConllectionTranslation::whereHas('newsTrans', function ($query) use ($title) {
$query->where('title', $title);
})->first();
Change your function like this
public function show($title)
{
$news = NewsConllectionTranslation::with(['newsTrans' => function ($query) use($title) {
$query->where('title', $title)->first();
}])
return View::make('portal.news.show', compact('news'));
}

Many-to-many (belongsToMany) Laravel relation doesn't seem to work under HHVM

MySQL tables:
posts
tags
post_tag (with columns post_id and tag_id)
// Post.php model
class Post extends Eloquent {
protected $table = 'posts';
public $timestamps = true;
protected $guarded = ['id'];
public function tags()
{
return $this->belongsToMany('Tag');
}
}
// Tag.php model
class Tag extends Eloquent {
protected $table = 'tags';
public $timestamps = false;
protected $guarded = ['id'];
public function posts()
{
return $this->belongsToMany('Post');
}
}
// on routes.php
Route::get('/', function()
{
$post = Post::find(44);
echo $post . '<br>';
$tag = Tag::find(28);
echo $tag;
return $post->tags;
});
when hitting / it prints post:44, it prints tag:28 and gives
ErrorException Cannot use a scalar value as an array
when accessing tags property that is on Post.php tags() function.
bare in mind that on post_tag's table there's an entry with post_id=44 and tag_id=28 but it could be empty.
Laravel/php gives me that error while trying to access the belongsToMany('Tag') method.
what am I doing wrong?
Should be fixed on February update: http://www.hhvm.com/blog/3287/hhvm-2-4-0
I believe you need to use eager loading:
$post = Post::with('tag')->find(28);
I don't have a laravel setup in front of me to test. So find might not be chainable, so you might need to do this:
$post = Post::with(array('tag' => function($query)
{
$query->where('id', '=', 44);
}))->get();

How to use the `where` method along with the `with` method in laravel 4?

Given the following, very simple, example:
Country Class
class Country extends Eloquent {
protected $table = "countries";
protected $fillable = array(
'id',
'name'
);
public function state() {
return $this->hasMany('State', 'country_id');
}
}
State Class
class State extends Eloquent {
protected $table = "states";
protected $fillable = array(
'id',
'name',
'country_id' #foreign
);
public function country() {
return $this->belongsTo('Country', 'country_id');
}
}
How can I list all the states, based on the id or the name of the country.
Example:
State::with('country')->where('country.id', '=', 1)->get()
The above returns an area, as country is not part of the query (Eloquent must attach the join later, after the where clause).
I think you're either misunderstanding the relations or over-complicating this.
class Country extends Eloquent {
public function states() {
return $this->hasMany('State', 'state_id');
}
}
$country = Country::find(1);
$states = $country->states()->get();

Categories