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;
Related
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();
I have a problem with a many to many relationship and the translations of the terms.
I have 4 tables:
products
- id, price, whatever
products_lang
- id, product_id, lang, product_name
accessori
- id, active
accessori_lang
- id, accessori_id, lang, accessori_name
I'm trying to assign accessories to products with an intermediate table named:
accessori_products
this is the model for Product:
class Product extends Model {
protected $table = 'products';
public function productsLang () {
return $this->hasMany('App\ProductLng', 'products_id')->where('lang','=',App::getLocale());
}
public function productsLangAll() {
return $this->hasMany('App\ProductLng', 'products_id');
}
public function accessori() {
return $this->belongsToMany('App\Accessori', 'accessori_products');
}
}
this is the model for productLng:
class ProductLng extends Model {
protected $table = 'products_lng';
public function products() {
return $this->belongsTo('App\Product', 'products_id', 'id');
}
}
Then I have the model for Accessori:
class Accessori extends Model {
protected $table = 'accessori';
public function accessoriLang() {
return $this->hasMany('App\AccessoriLng')->where('lang','=',App::getLocale());
}
public function accessoriLangAll() {
return $this->hasMany('App\AccessoriLng');
}
public function accessoriProducts() {
return $this->belongsToMany('App\Products', 'accessori_products', 'accessori_id', 'products_id');
}
}
And the model for AccessoriLng:
class accessoriLng extends Model {
protected $table = 'accessori_lng';
public function accessori() {
return $this->belongsTo('App\Accessori', 'accessori_id', 'id');
}
}
I get the results by this:
$products = Product::has('accessori')->with([
'productsLang ',
'accessori' => function ($accessori){
$accessori->with([
'accessoriLang'
]);
}
])->get();
return $products;
but I want to get only the active accessories something like where accessori.active = 1 but I really don't know where to put it. I've tried in different way but I'm stuck on it by 2 days.
IIRC you don't need a model for the intermediate table on your many to many relationships.
If you want to return Products where Accessori is active you can use whereHas on the Product model.
$prod = Product::whereHas('accessori', function($query) {
$query->where('active', 1);
})->get();
Where the $query param will be running on the Accessori model.
You can do the inverse as well with Accessori to Product.
$acessoris = Accessori::where('active', 1)->whereHas('accessoriProduct')->with(['accessoriLang', 'accessoriProducts.productsLang'])->get();
In my application, Users can have many products. Now, i am trying to display the users phone number for a every displayed products.
In my products table, there is a column user_id for the respective users.
This is how my model looks like
User Model
public function products()
{
return $this->belongsTo('Models\Database\User','user_id');
}
Product Model
class Product extends BaseModel
{
protected $fillable = ['user_id','type', 'name', 'slug', 'sku', 'description',
'status', 'in_stock', 'track_stock', 'qty', 'is_taxable', 'page_title', 'page_description'];
// protected $guarded = ['id'];
public static function getCollection()
{
$model = new static;
$products = $model->all();
$productCollection = new ProductCollection();
$productCollection->setCollection($products);
return $productCollection;
}
public function users()
{
return $this->hasMany('\Models\Database\Product');
//->withTimestamps();
}
public function categories()
{
return $this->belongsToMany(Category::class);
}
public function reviews()
{
return $this->hasMany(Review::class);
}
public function prices()
{
return $this->hasMany(ProductPrice::class);
}
public function orders()
{
return $this->hasMany(Order::class);
}
public function users()
{
return $this->hasMany('Models\Database\Product');
}
And in my view, this is how i try to get the respective user's phone number
<p>{{$product->users->phone}}</p>
But i get an error like
SQLSTATE[42S22]: Column not found: 1054 Unknown column
'products.product_id' in 'where clause' (SQL: select * from products
where products.product_id = 1 and products.product_id is not
null)
You should do:
User Model
public function products()
{
return $this->hasMany('Models\Database\Product');
}
Product Model
public function user()
{
return $this->belongsTo('Models\Database\User');
}
In your blade:
{{ $product->user->phone }}
You have got your relationship models inverted,
change them:
In your User model:
public function products()
{
return $this->hasMany('Models\Database\Product');
}
In your Product model:
public function user()
{
return $this->belongsTo('Models\Database\User','user_id');
}
And then you could access the properties like:
<p>{{$product->user->phone}}</p>
Link to the Docs
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();
I'm trying to retrieve data from many to many relationship.I have two tables :
companies: [cid,name,origin]
vehicle_types: [id, type]
their pivot table: companies_vehicle_types: companies_id,vehicle_types_id Relationship defined: In Companies:
class companies extends Model
{
//
protected $fillable = ['name','origin'];
protected $primaryKey = 'cid';
public function vehicles(){
return $this->hasOne('App\vehicles');
}
public function vehicle_types(){
return $this->belongsToMany('App\vehicle_types', 'companies_vehicle_types', 'companies_id', 'vehicle_types_id');
}
}
In vehicle_types
class vehicle_types extends Model
{
//
protected $fillable = ['type'];
public function vehicles(){
return $this->belongsTo('App\vehicles');
}
public function companies(){
return $this->belongsToMany('App\companies','companies_vehicle_types','vehicle_types_id','companies_id')->withTimestamps();
}
}
I want to retrieve companies where vehicle_types = specific type. How can i do that? I tried doing following in my controller:
$vehicle_types=vehicle_types::where('type','Bike')->get();
foreach ($vehicle_types as $vehicle_type) {
# code...
foreach ($vehicle_type->companies as $company) {
$brand[]=$company->pivot->name;
}
}
return $brand;
But it doesn't seem to be working. $vehicle_types is working fine and returning value. $brand is not returning any value.