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
Related
I can't resolve this relation with eloquent. I don't know, maybe it is illegal relation. But I can't think of another relationship. I need one CustomerCodeReferences row from SaleProduct row.
Why not:
class CustomerCodeReference extends Model
{
public function saleProducts()
{
return $this->hasMany(\App\Models\SaleProduct::class, 'product_id', 'product_id');
}
public function documents()
{
return $this->hasMany(\App\Models\Document::class, 'customer_id', 'customer_id');
}
public function scopeCustomer($query, int $customer)
{
$query->where('customer_id', $customer);
}
}
class Document extends Model
{
public function saleProducts()
{
return $this->hasMany(\App\Models\SaleProduct::class);
}
public function customerCodeReferences()
{
return $this->hasMany(\App\Models\CustomerCodeReference::class, 'customer_id', 'customer_id');
}
}
class SaleProduct extends Model
{
public function customerCodeReferences()
{
return $this->hasMany(\App\Models\CustomerCodeReference::class, 'product_id', 'product_id');
}
public function documents()
{
return $this->belongsTo(\App\Models\Document::class);
}
}
The Project's CustomerCodeReferences can be accessed like this:
$project->customerCodeReference()->customer(1)->get();
How can I fetch data along with blog category and blog tags from Blogs table using with in query.
Below is my model and controller code, I am getting Get Blogs Api Error instead of the blogs data.
Blog Controller
public function getBlogs()
{
try {
$blogs = Blog::where('status', 1)
->with('category')
->with('tag')
->with('user')
->with('comment')
->orderBy('id', 'desc')
->paginate(5);
return response()->json($blogs);
} catch (\Illuminate\Database\QueryException $e) {
$e = "Get Blogs Api Error";
return response()->json($e);
}
}
Blog Model
class Blog extends Model
{
public function user()
{
return $this->belongsTo(User::class);
}
public function category()
{
return $this->hasMany(Category::class);
}
public function tag()
{
return $this->hasMany(Tag::class);
}
public function comment()
{
return $this->hasMany(Comment::class);
}
}
User Model
public function blog_user()
{
return $this->hasMany(Blog::class);
}
Blog Category Model
public function blog_category()
{
return $this->belongsTo(Blog::class);
}
Blog Tag Model
public function blog_tag()
{
return $this->belongsTo(Blog::class);
}
Blog Comment Model
public function blog_comment()
{
return $this->belongsTo(Blog::class);
}
Database table structure
blogs table structure
blog_categories table structure
blog_tags table structure
First of all change names to plural. not singular. as you are using one to many. and use belongsToMany() method. not hasMany().
public function categories(){
return $this->belongsToMany(Category::class);
}
and change the name of pivot table to blog_category not blog_categories. It will work. and your BlogCategory model will look like this.
class BlogCategory extends Model {
protected $table = 'blog_category';
public function blog() {
return $this->belongsTo( Blog::class );
}
}
now you can get blogs like this.
$blogs = Blog::with( 'categories' )->get();
and this is how you will fetch blog for any category.
$category = BlogCategory::where( 'category_id', $category->id )->first();
dd( $category->blog );
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();
I have three tables:
products
product_types
product_categories
products belongs to product_types and product_types belongs to product_categories.
How can I access a column from product_categories from products?:
ProductTypes model:
class ProductTypes extends Eloquent {
public function category() {
return $this->belongsTo('ProductCategories');
}
}
Products model:
class Product extends Eloquent {
protected $table = 'products';
public function brands() {
return $this->belongsTo('ProductBrands', 'brand_id', 'id');
}
public function ages() {
return $this->belongsTo('ProductAges', 'age_id', 'id');
}
public function types() {
return $this->belongsTo('ProductTypes', 'type_id', 'id');
}
public function images() {
return $this->hasMany('ProductImages');
}
public function reviews() {
return $this->hasMany('ProductReviews');
}
public function toArray() {
$ar = $this->attributes;
$ar['brand'] = $this->brand;
$ar['age'] = $this->age;
$ar['type'] = $this->type;
return $ar;
}
public function getBrandAttribute() {
$brands = $this->brands()->first();
return (isset($brands->brand) ? $brands->brand : '');
}
public function getAgeAttribute() {
$ages = $this->ages()->first();
return (isset($ages->age) ? $ages->age : '');
}
public function getTypeAttribute() {
$types = $this->types()->first();
return (isset($types->type) ? $types->type : '');
}
}
I have tried:
$productData->types()->category()->category
But this gives an error saying the method doesn't exist.
Sorry about the title, couldn't think of one.
The problem is, that you're not executing the query when doing types() and therefore you're calling category() on the query builder instance and not the ProductTypes model.
You can use the dynamic properties for accessing the result of the relationship.
$productData->types->category->category
Also consider renaming your relationships. Currently you have "types" for example but it only returns one type, because its a one-to-many relation. "type" would make more sense.