Eloquent Relationship - php

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

Related

Laravel - Eloquent Relationship not working One to Many relationship

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');
}

Php Laravel pass variable from controller to model

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 to get data for one to many relationship using Eloquent in Laravel?

How to get data for one to many relationship using Eloquent in Laravel? Actually I followed Eloquent Documentation. But my code returns me an empty array. Here's my work:
Database Schema
Parent Table: mtg_workspace with columns (mw_id[primary key], mw_name,..., mw_access)
Child Table: mtg_workspace_amenities with columns (id[primary key], wa_mwid, wa_name)
Model: MtgWorkspace.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MtgWorkspace extends Model
{
protected $table = 'mtg_workspace';
public $timestamps = false;
public function MtgWorkspaceAmenities(){
return $this->hasMany('App\MtgWorkspaceAmenities', 'wa_mwid');
}
}
Model: MtgWorkspaceAmenities.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MtgWorkspaceAmenities extends Model
{
protected $table = 'mtg_workspace_amenities';
public $timestamps = false;
public function MtgWorkspace(){
return $this->belongsTo('App\MtgWorkspace');
}
}
Controller: WorkspaceController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MtgWorkspace;
use App\MtgWorkspaceAmenities;
class WorkspaceController extends Controller
{
public function index()
{
$workspace = MtgWorkspace::with('MtgWorkspaceAmenities')->get();
return $workspace;
}
}
and here it shows following output:
Can you try defining the primary key for the MtgWorkspace model (as it is not id):
protected $primaryKey = 'mw_id';
I don't think it can match up the children MtgWorkspaceAmenities to the parent MtgWorkspace models as it is trying to use the id attribute on MtgWorkspace to match to the foreign key on MtgWorkspaceAmenities when it spins through the result of the eager loading.
Side Note:
You will have to pass more parameters to the inverse relationship on MtgWorkSpaceAmenities when defining it, as belongsTo() wants to use the calling methods name snake cased with _id added if not told otherwise as the key.

how to get all rows where specific column = id of other row in different table

I am trying to get all rows in a payments table where I have another table called projects I want to get all rows that in payments table where project_id column = ID of the row inside projects table I am using Laravel framework please help me this some the code
Payment Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Payment extends Model
{
protected $table = 'payments';
public function projects() {
return $this->belongsTo('App\Project');
}
}
Project Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Project extends Model
{
protected $table = "projects";
public function payments() {
return $this->hasMany('App\Payment');
}
}
Route File
Route::get('special/{project_id}', 'SpecialController#index');
The index function in the Controller
<?php
namespace App\Http\Controllers;
use App\Project;
use App\Payment;
use Illuminate\Http\Request;
class SpecialController extends Controller
{
/**
* Display a listing of the resource.
*
* #return \Illuminate\Http\Response
*/
public function index(Project $project_id)
{
return view('special.index')->with(['projects' => $project_id]);
}
This is my problem please help
All the best 😀
In your controller, I see that u have injected an instance if Project, but named as $project_id. Thats not an id, id would have been resolved to an instance of Project.
public function index(Project $project_id)
just a note. use index method to show the listing, unless its a nested resource.
public function index(Project $project)
{
//assuming that $project is an instance of Project
$project = $project->with('payments')->get();
//$project will now include the related payments as well
//if you want to check do this, for debugging uncomment next line
//dd($project->toArray());
return view('special.index')->with(['project' => $project]);
}
whats happening in code is that $project is retrieved with its related payments. in with('payments') the 'payments' is the name of the relationship.

Relationship table not recognized in Laravel 5

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.

Categories