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');
}
}
Related
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
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 have two models:
class Order extends Eloquent
{
public function User()
{
return $this->belongsTo('User');
}
public function Product()
{
return $this->belongsToMany('Product');
}
}
and the second one is:
class Product extends Eloquent
{
public function Order()
{
return $this->belongsToMany('Order');
}
}
My question is how can i access a value of second table column using pivot table:
product table:
id
title
image
order table:
id
status
pivot table(order_product):
id
product_id
order_id
I need to access title column of products from orders. for example if a user orders many products in one order I can fetch all product title and show theme.
I don't like use join , instead I like to use Laravel functionality itself.
I found the answer:
$orders = Order::orderBy('created_at', 'DESC')->paginate($page_number);
foreach($orders as $item){
foreach($item->product as $item){
{{$item->title}}<br>
}
}
I can access products from order.
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.
I've got the following tables:
products (
id
)
attributes (
id
name
value
)
products_attributes (
product_id,
attribute_id
)
And I need to be able to query for all of the attributes of a specific product. I tried doing this with the FLUENT QUERY BUILDER but I'm getting lost in my own code.
Can someone help me out with an example?
Usually you would create models for both of your entities, in which you can specify the relationships:
class Product extends Eloquent
{
protected $table = 'products';
public function attributes()
{
return $this->belongsToMany('Attribute', 'products_attributes');
}
}
class Attribute extends Eloquent
{
protected $table = 'attributes';
public function products()
{
return $this->belongsToMany('Product', 'products_attributes');
}
}
The belongsToMany() method sets up a many-to-many relationship. The first parameter specifies the related model class name, the second one the name of the database table that holds the connections between the two entities.
To find a product with ID 1234, you would fetch it like this:
$product = Product::find(1234);
You can then magically access all of its attributes like this:
$attributes = $product->attributes;
For more information, you can refer to the documentation.