I have been working on integrating Laravel's Eloquent relationship on my Code Igniter project. So I followed the steps in http://jamieonsoftware.com/post/90299647695/using-eloquent-orm-inside-codeigniter-with-added . Everything is working fine. But When I started mapping relationships, I get error like
Fatal error: Call to undefined method Products::hasMany()
Following is my Product model file
use \Illuminate\Database\Eloquent\Model as Eloquent;
class Product extends Eloquent{
protected $table = "products";
public function getActive(){
return Product::where('status', 1)->get();
}
public function Price(){
return $this->hasMany('Price', 'product_id');
}
}
And this is my Price model
use \Illuminate\Database\Eloquent\Model as Eloquent;
class Price extends Eloquent{
protected $table = "price";
}
How to fix this issue?
you have to call it:
$product = Product::with('price')->get();
or
$product = Product::all();
$productPrice = $product[0]->price;
not
$product = Product::Price();
Some info:
If you have a 1:n relation you can define it better "prices":
public function prices(){
return $this->hasMany('Price', 'product_id');
}
it is better for reading if a product has more then one price:
$product = Product::with('prices')->find(1);
Related
I'm new in laravel framework. I couldn't get work medicine with prices in controller.
My model;
use Illuminate\Database\Eloquent\Model;
class Medicine extends Model
{
protected $table = 'medicine';
protected $fillable = [];
protected $guarded = [];
public function withPrice()
{
return $this->hasMany('App\Models\MedicinePrice', 'medicine_id', 'id');
}
}
In my app service ;
public function getRecentEntries()
{
$medicines = Medicine::orderBy('id','DESC')->take(10)->get()->toArray();
dd($medicines);
return $this->formatMedicine($medicines);
}
Table of medicine : https://take.ms/EHrwd
Table of medicine_price : https://take.ms/BMTJW
Any helps ? Thank you so much.
You are never loading the relationship in your code. You can accomplish it with:
Medicine::with('withPrice')->get();
However, the with('withPrice') sounds a little weird doesn't it? I would recommend you to rename the method of your relation in your Medicine model to something prettier, like prices:
public function prices()
{
return $this->hasMany(MedicinePrice::class);
}
And then you can retrieve the medicine with the prices like this:
$medicines = Medicine::with('prices')->orderByDesc('id')->take(10)->get()->toArray();
You can read more about eager loading here: https://laravel.com/docs/6.x/eloquent-relationships#eager-loading
I'm using laravel
I have two models
Product
class Product extends Model
{
public function productcategories(){
return $this->hasOne('App\Product\Productcategorie','CategoryID','ProductCategoryId');
}
}
and Productcategorie
class Productcategorie extends Model
{
protected $primaryKey = 'CategoryID';
public function product(){
return $this->belongsToMany('App\Product\Product','ProductCategoryId','CategoryID');
}
public function scopeCp($query,$id){
return $query->where('categoryparent_id', '=', $id);
}
}
The Product model has a scope Cpscope
and i have ProductController with function
function productCatgoryPaFilter(Request $request){
$categories= Categoryparent::with('categories')->get();
$id=$request->id;
return $product = Product::with('productcategories')->with('productoption.option')->orderBy('created_at','DESC')->get();
}
i want to get all products with categoryparent_id equal to passed parametre in scope
how can i do it?
If you want to filter data in relational model, use whereHas(). Though i have not tested, give it a try
Product::whereHas('productcategories', function ($query) use($id) {
$query->cp($id);
})
->orderBy('created_at','DESC')->get()
I like to list all MovimentoProdutoUnidade that movimento_id = 3 using the hasMany function.
My Model Movimento:
use Illuminate\Database\Eloquent\Model;
use App\Unidade;
class Movimento extends Model
{
protected $fillable = [
"movimento", "descricao", "requisitante", "despachante", "data", "unidade_ori_id", "unidade_des_id"
];
protected $table = "movimentos";
public function movimentoProdutoUnidade(){
return $this->hasMany('App\MovimentoProdutoUnidade', 'movimento_id');
}
}
My Model MovimentoProdutoUnidade
use Illuminate\Database\Eloquent\Model;
use App\Movimento;
class MovimentoProdutoUnidade extends Model
{
protected $fillable = [
"movimento_id", "unidadeProduto_id"
];
protected $table = "movimento_produtounidades";
public function movimento(){
return $this->belongsTo('App\Movimento', 'movimento_id');
}
}
My Controller:
public function licitacao(Request $request){
$movimentos = Movimento::where('unidade_ori_id', 3)->movimentoProdutoUnidade;
dd($movimentos);
//return view('relatorios.licitacao', compact('movimentos'));
}
The dd fuction return
Undefined property: Illuminate\Database\Eloquent\Builder::$movimentoProdutoUnidade
Your error is because you're not calling first() on the query builder object, so you have an instance of Builder (which does not have a $movimentoProdutoUnidade property) instead of a Movimento model:
$movimento = Movimento::where('unidade_ori_id', 3)->first();
$movimento_produto_unidade = $movimento->movimentoProdutoUnidade;
However, if you want all MovimentoProdutoUnidade, try thinking "backwards":
$movimento_produto_unidade = MovimentoProdutoUnidade::whereHas('movimento', function ($query) {
return $query->where('unidade_ori_id', 3);
})
->get();
As stated in the comment i made, try using first function like this:
Movimento::where('unidade_ori_id', 3)->first()->movimentoProdutoUnidade;
Remember always after the condition use get(), first() or find() functions to pull the data from the database.
Take a look to this link
Hi I want to make relationship between two tables first Table is product and second is productimages
ProductController.php
public function product(){
$products = Product::all();
dd($products->images);
}
Product.php (modal)
class Product extends Model
{
public $timestamps = false;
//
public function images()
{
return $this->hasOne(ProductImage::class);
}
}
ProductImage.php(model)
class ProductImage extends Model
{
public function product(){
return $this->belongsTo(Product::class);
}
}
When i am using this method $products = Product::find(1); working find but i need all.
Thanks
When you're doing $products->images you're trying to access property of collection.
Preload all products with their images, use with() method:
$products = Product::with('images')->get();
Then you'll be able to get image of each product and avoid N + 1 problem:
#foreach ($products as $product)
// Access $product->image here
#endforeach
Product::with('images')->get();
I'm trying out this model-thing, but I can't really get my grasp of it.
For the moment I have two tables (companies and sellers) "companies" as a column named "cResponsibleID" which I want to map to "sID" in "sellers".
models/Companies.php
class Companies extends Eloquent {
protected $table = 'companies';
protected $primaryKey = 'cID';
public function sellers() {
return $this->belongsTo('Sellers','sID');
}
}
models/Sellers.php
class Sellers extends Eloquent {
protected $table = 'sellers';
protected $primaryKey = 'sID';
public function companies() {
return $this->hasMany('Companies','cResponsibleID');
}
}
I then want to do something like Companies::with('sellers.sName')->get() to "translate" cResponsibleID to sName.
Maybe I'm all out wrong.
Thankful for all help.
Can you try printing the result of:
<?php
$company = Companies::with('sellers')->get();
echo '<pre>';
print_r($company->sellers);
And see how they're build up, I blieve the sellers.ANYTHING construction is only meant for multiple nested relations.
for example of a Seller has an Address as a relation, it would be Companies::with('sellers.address')