I have a table of articles defined by their ID, name, price and category_ID and a table of categories defined by category_ID and name.
I want to select into my controller, the list of articles, along with the category name.
How to do that?
My answer assumes you keep the models in App\Models folder
In your Articles model define the following method.
public function category()
{
return $this->belongsTo('App\Models\Category');
}
You can access it now via $myArticle->category->name;
Make sure in Categories model the correct table is defined, based on your question i can not make up the categorie table.
Put $table = 'categories'; in the category model or whatever the table name is.
with raw SQL
$query = "SELECT articles.* , categories.name AS categoryName FROM articles JOIN categories ON articles.category_ID = categories. category_ID"
$result = \DB::select(SQL);
dump($result)
or
with Eloquent you can add a method to your model to return relationship , let's call it category
class Article extends Model {
public function category(){
return $this->hasOne("App/Category" , "category_ID" , "category_ID");
}
}
now you can do this
$article = Article::find(1);
dump($article->category->name);
checkout hasOne method from the docs
Related
I am new to laravel & want to implement eloquent relationship.
Let me explain.
Consider I have 2 tables
products
product_id
product_name
brand_id
price
brands
id
brand_name
Each product will have one brand Id.But in Brands table, there is no product id. One brand_id can be in multiple product rows, and one product has one brand_id only. I want to select some col from products table plus brand_name with respect to brand_id of products table using Model.SO in Product model I wrote:
public function brands()
{
return $this->hasOne('App\Brand','product_id');
}
and in Brand model I write:
public function products()
{
return $this->belongsTo('App\Product','brand_id');
}
Now I want the result:
product_name
price
brand_name
How can I fetch those data in controller using eloquent relation? Also, the way I wrote Model relationship, Is it ok??
Your Product Model relation will be below
public function brand(){
return $this->belongsTo('App\Brand','brand_id');
}
public function product(){
return $this->belongsTo('App\Product','product_id');
}
Now in controller you can add query as below.
$products = Product::with('brand','product')->get();
echo '<pre>'
print_r($products->toArray());
exit;
It looks to me like you want a one-to-many relationship, so one brand can have many products and many products belong to one brand.
Product model:
public function brand()
{
return $this->belongsTo('App\Brand');
}
Brand model:
public function products()
{
return $this->hasMany('App\Product');
}
Then you would be able to get the brand information like this:
The full brand model:
Product::first()->brand
The brand name:
Product::first()->brand->brand_name
From the docs:
A one-to-many relationship is used to define relationships where a
single model owns any amount of other models. For example, a blog post
may have an infinite number of comments.
P.S.:
Your table column names do not make much sense to me, why do you have product_id on products but then on brands it is just called id? Why do you have product_name but then just price? why is it not just name or product_price, so your at least consistent?
I have two tables in Laravel Eloquent:
UserCategory:
id | user | category
and
Category:
id | name
UserCategories relates to Category trough belongsTo:
class UserCategory extends Model
{
public function category()
{
return $this->belongsTo('App\Category', 'category');
}
}
But when I try to get UserCategories with Categories I got integer value (instead of Category model)
$categories = [];
$userCategory = UserCategory::where('user', $user->id)->with('category')->get();
foreach($userCategory as $item) {
$categories[] = $item->category->name;
}
When I try to get the category's name I see the second error:
Trying to get property 'name' of non-object
Curious thing, that when I use dd($item) I see that $item has correct relation to Category object, but dd($item->category) returns integer value (category id) instead of category model.
You have conflicting names. You have both a category column, and a category relationship. By saying $item->category its showing you the category column value. Try changing the relationship name to something else and see if that works.
The best practice would be to use a column name of category_id, but if changing the column name isn't feasible in your situation then the relationship name will work just as well.
Change your relation name or id name here because here your relation name & coloumn name is same
class UserCategory extends Model
{
public function category()
{
return $this->belongsTo(Category::class, 'category');
}
}
I'm still a beginner in Laravel. I'm trying to write a query to get categories which are associated with specific place. I have the following three tables
place place_categorye category
------ ---------------- -------------
id place_id id
name category_id name
each place has number of categories
what I want to do is when I choose place_id I get the categories associated with it in the pivot table.
I supposed that you have a Many To Many relation between places and categories then in your Place Model
public function categories(){
return $this->belongsToMany(Category::class, 'place_categorye', 'place_id', 'category_id');
}
And now you can access the categories of a certain Place like below:
$place->categories;
Without the relationship definitions, it is hard to give an answer on the ORM queries, but here is a raw query which will give you the expected result,
DB::select(DB::raw("
select category.id, category.name
from place
join place_categorye on place_categorye.place_id = place.id
join category on category.id = place_categorye.category_id
where place.id = 1");
if you want the results inclusive of all the null values, depending on the use case you can use a left join instead of join (join means innter join by default)
** to many relationship** for this
<?php
namespace App\PlaceCategory;
use Illuminate\Database\Eloquent\Relations\Pivot;
class PlaceCategory extends Pivot {
public function place()
{
return $this->belongsTo('App\Place');
}
public function category()
{
return $this->belongsTo('App\Category');
}
}
category Model
public function places()
{
return $this->hasMany('App\Place')
->using('App\PlaceCategory');
}
Place Model
public function categpries()
{
return $this->hasMany('App\Category')
->using('App\PlaceCategory');
}
Now you can access this easily & can query easily .
Like
$place=Place::with('categories')->first();
by using
$place->categories we get all the categories for this place
I have the following models
Category
id // we don't want to use this one for the relation
category_id // we want to use this
Product
id
CategoryProduct
product_id // points to "id" on products table
category_id // points to **category_id** on categories table
I have the Product model set up as follows (only the most recent variation).
class Product {
public function categories() {
return $this->belongsToMany('Category', 'categories_products', 'category_id');
}
}
When I try to get a product with categories as follows...
Product::with('categories')->get();
I either get the wrong categories because the query is using id on categories as the foreign key. I need it to be using category_id on the categories table.
Or I get none at all. I can't seem to hash out how to set up which columns to use on the belongsToMany method.
Try this follow,
class Product {
public function categories() {
return $this->belongsToMany('Category', 'categories_products', 'product_id','category_id');
}
}
I am trying to use Eloquent to get a specific product that has a brand_id column that maps to a brands table, the brand array is coming back empty.
Is there anything obvious here that needs to be changed?
$product = Product::with('images')->with('brand')->select($fields)->where('display', '=', 1)->find($id);
//Product model
class Product extends Eloquent {
...
public function brand()
{
return $this->belongsTo('Brand');
}
//Brand model
class Brand extends Eloquent {
...
public function products()
{
return $this->hasMany('Product');
}
You have this:
$product = Product::with('images', 'brand')
->select($fields)
->where('display', 1)
->find($id);
You are getting null for brand and it could be because you have some specific fields and most probably you didn't select the foreing_key from the products table that creates the relationship with Brand, so if your products table contains the foreign_key (probably brand_id) of brand table then you have to select that foreign_key from the products table too. So, just add that foreign_key/brand_id in the $fields variable. Without the relation builder key (FK) the Brand won't be loaded.