I have defined the following relationships to my models A & B:
Model A
namespace App;
use Illuminate\Database\Eloquent\Model;
class A extends Model {
protected $table = 'list';
public function b(){
return $this->hasMany('App\B', 'id', 'id');
}
}
Model B
namespace App;
use Illuminate\Database\Eloquent\Model;
class B extends Model
{
protected $table = 'project';
public function a(){
return $this->belongsTo('App\A', 'id', 'id');
}
}
I am trying to get the sum from the model B based on the selection from the model A. However, it returns an error as Undefined property: Illuminate\Database\Eloquent\Collection::$b
Controller
public function index()
{
$all = A::all()->count();
$large = A::where('class', 'L')->count();
$medium = A::where('class', 'M')->count();
$lg = A::where('class','L')->get();
$amount = $lg->b->sum('value');
return view('srl')->with('large', $large)
->with('medium',$medium)
->with('all',$all)
->with('amount',$amount);
}
The problem is in this line $amount = $lg->b->sum('value');. The relationship seems not working due to some reason. Any suggestions would be appreciated.
You're trying to get a relationship on a collection, the relationship exists on the objects (records) inside that collection. You need to loop over the $lg results, and for each one get their b values.
Something like this:
$lg = A::where('class','L')->get();
$amount = 0;
foreach($lg as $item)
{
$amount += $item->b->value;
}
Thanks #James ... I had to double loop to get it work. I don't know why I had to loop it twice.
Related
I have two models with One-to-Many relationship. I want to display data with relationship in blade.
Products Table
Table name = Products
PrimaryKey = pro_id
ForeignKey = cat_id
Categories Table
Table name = categories
PrimaryKey = cat_id
Products Model Code
namespace App;
use Illuminate\Database\Eloquent\Model;
class productsModel extends Model
{
//code...
protected $table = 'products';
protected $primaryKey = 'pro_id';
// Every Products Belongs To One Category
public function category()
{
# code...
return $this->belongsTo('APP\abcModel','cat_id');
}
}
Categories Model Code
namespace App;
use Illuminate\Database\Eloquent\Model;
class categoryModel extends Model
{
//code...
protected $table = 'categories';
protected $primaryKey = 'cat_id';
// One Category Has Many Products
public function products()
{
# code...
return $this->hasMany('App\productsModel','cat_id','pro_id');
}
}
Controller Code
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\productsModel;
class productsController extends Controller
{
//code...
public function products($category_id='')
{
# code...
$data["products"] = productsModel::where
('cat_id',$category_id)
->get();
$data["categories"] = productsModel::where
('cat_id',$category_id)->first()->category;
echo "<pre>";
print_r($data);
echo "</pre>";
}
}
ERROR:
Symfony\Component\Debug\Exception\FatalThrowableError
Class 'APP\categoryModel' not found
Seems that sometimes you have App, sometimes APP, while PHP is not case sensitive on class names, you might use an operating system (Linux?) that is case sensitive in terms of file names.
I would recommend to have only App everywhere, your error message clearly indicates: APP.
You can clearly see in your model files the namespace is written as "namespace App;"
There you defined the namespace for the app folder. So when you are using this model anywhere, you need to write it as you have defined the namespace. Therefore "App\categoryModel".
Your code should be as follows:
public function category()
{
# code...
return $this->belongsTo('App\categoryModel','cat_id');
}
Also a sincere request, as #alithedeveloper mentioned please follow PSR standards for writing code.
public function category()
{
return $this->belongsTo(abcModel::class,'cat_id');
}
public function products()
{
return $this->hasMany(productsModel::class,'cat_id');
}
Why i am getting error for Laravel relationship. I am trying to print_r the values with this relationship. is there any way to get rid of this error?
Controller: this is cart page functions
public function cart_page()
{
$session_id = Session::get('session_id');
$viewData = cartmodel::with('product_tbls')->where('session_id', $session_id)->get();
echo "<pre>";
print_r($viewData);
die;
// return view('pages.cart', compact('viewData'));
}
Products_model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class product_models extends Model
{
protected $table = "product_tbls";
public function shop_product_all()
{
return $this->hasMany('App\cartmodel');
}
}
Cart model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class cartmodel extends Model
{
protected $table = "shoppingcart";
public function shopcart_product()
{
return $this->belongsTo('App\product_models');
}
}
You're calling a relationship which isn't defined. I think you're passing table name in with which should be relationship function as vivek_23 mentioned in comment. So try the below code:
public function cart_page()
{
$session_id = Session::get('session_id');
$viewData = cartmodel::with('shopcart_product')->where('session_id', $session_id)->get();
echo "<pre>";
print_r($viewData);
die;
// return view('pages.cart', compact('viewData'));
}
After fixing with('shopcart_product'), I just append product_id in model like,
public function shopcart_product()
{
return $this->belongsTo('App\product_models', 'product_id);
}
Now getting values from product_tbls
I'm very new to laravel and I'm really struggling here.
So the thing that i am trying to to is , pass the {wildcard} to in a DB query that's in the model
My Code
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Product extends Model
{
protected $table = "product";
public $timestamps = false;
public function scopeSingleProduct($id){
$products = DB::select("SELECT * FROM product WHERE id = '$id'");
return $products;
}
}
Controller
public function show($id){
$product = Product::SingleProduct($id);
return view('products.product',compact("product"));
}
View
{{ $product }}
So my code basically works if i set $id to a static number in the model file e.g. 1,2,3,4 etc. but it just doesn't seem to work properly here, can someone tell me what i am doing wrong?
TRY THIS
Model
namespace App;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
class Product extends Model
{
protected $table = "product";
public $timestamps = false;
//create relationships, that's it, no need to write queries
}
Controller
public function show(Request $request){
//$request->id is the product id, you can pass it through query string or by post
if($request->id>0){
$product = Product::where('id', $request->id)->first();
return view('products.product',compact("product"));
}
}
View
{{ $product }}
How can i create a method in my model below that consist of first value of pages?
I want my cover method to get he first instance of pages.
Here's my model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Book extends Model
{
protected $guarded = [];
public function pages()
{
return $this->hasMany('\App\Page');
}
public function cover()
{
//first page of pages here
}
}
Use the first() method on the relationship
public function cover()
{
return $this->pages()->first();
}
Why am I getting this error for such a simple relationship query?
Call to undefined method Illuminate\Database\Query\Builder::country()
I just want to get a list of lookup values from my lookup table called pc_country. I have even included the namespaces!
Controller;
$tableName = $postcode_tablename->dataset; //eg 201502_postcode
$country = PostcodeExtract::fromTable($tableName)
->country() //this is generating the error!
->distinct()
->select('description')
->get();
var_dump($country);
exit;
Country Model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Country extends Model {
protected $connection = 'postcodes';
public $table = 'pc_country';
protected $fillable = ['description', 'country_id', 'code'];
public function postcodeExtract()
{
return $this->hasMany('App\Models\PostcodeExtract');
}
}
PostCode Extract Model;
<?php namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class PostcodeExtract extends Model {
protected $connection = 'postcodes';
protected $fillable = ['country'];
public function scopeFromTable($query, $tableName)
{
return $query->from($tableName);
}
public function country()
{
return $this->belongsTo('App\Model\Country');
}
}
My 201502_postcode table has a country_id and my pc_country table has a id field for it to do the lookup on. Is that correct? I don't see the problem...
You used fromTable method(scope) it returns eloquent query builder so your relations wont be available. Consider same code without calling that method.
If you want to change table of model create an instance and then call setTable method on the created instance then use your instance to query
$instance = new PostCodeExtract();
$instance->setTable ("table");
$country = $instance->country()->........
Sorry im on mobile couldn't provide good example code but you can achieve it with this method