Laravel eloquent One to Many relation - php

I cannot figure out how to define one to many relation using Eloquent.
Here are tables
----------- Country -----------
id | title | code | currency_code
----------- Currency Code --------
id | name | symbol | code
One country may have many currencies.
Therefore I defined my models as follows
class Country extends Model
{
public function currencies()
{
$this->hasMany('App\Models\Currency', 'code', 'currency_code');
}
}
And the Currency model is simple
class Currency extends Model
{
}
And I am selecting countries like that
return Country::all('country_id AS value', 'title_ru AS title','currency_code')
->sortBy('value');
But it returns null when I try to access currencies
What is wrong with my definitions, I would be grateful for any help.
Thanks

You can set your model like the following code:
Country model:
class Country extends Model
{
protected $table = 'country';
protected $primaryKey = 'id';
public function currency(){
return $this->hasMany(App\Models\Currency', 'code', 'currency_code');
}
}
Currency model:
class Currency extends Model
{
protected $table = 'currency';
protected $primaryKey = 'id';
public function country(){
return $this->belongTo('App\Models\Country', 'code');
}
}
And then if you wanna get a specific country data (with currency) you can use this:
$data = County::where('id','=',$id)->with('currency')->first();
Or if you wanna get everything you can use:
$data = County::with('currency')->get();

You should try this:
Country Model
class Country extends Model
{
public function currencies()
{
$this->belongsTo('App\Models\Currency', 'currency_code');
}
}
Currency Model
class Currency extends Model
{
public function country()
{
$this->belongsTo('App\Models\Country');
}
}

Related

Laravel 6 - Illuminate\Database\Eloquent\RelationNotFoundException Call to undefined relationship

I want to send nama column from Supplier table to Transaction_in table, but iget this error.
Illuminate\Database\Eloquent\RelationNotFoundException Call to
undefined relationship [get_transactions_in] on model
[App\Transaction_in].
Transaction_in Model
class Transaction_in extends Model
{
protected $guarded = [];
public function get_suppliers(){
return $this->belongsTo(Supplier::class, 'Supplier_id');
}
}
Supplier Model
class Supplier extends Model
{
protected $guarded = [];
public function get_transactions_in(){
return $this->hasMany(Transaction_in::class);
}
}
Transaction_in Controller
public function index()
{
$transaction_ins = Transaction_in::with('get_transactions_in')->get();
return view('transactionsIN.index', compact('transaction_ins', $transaction_ins, 'supplierList'));
}
The foreign key is Supplier_id based on id from Supplier table.
You called wrong relationship in with it should be get_suppliers instead of get_transactions_in
Transaction_in Model has get_suppliers method so,
$transaction_ins = Transaction_in::with('get_suppliers')->get();
just change your controller code with below
public function index()
{
$transaction_ins = Transaction_in::with('get_suppliers')->get();
return view('transactionsIN.index', compact('transaction_ins', $transaction_ins, 'supplierList'));
}
you got an error because there is no relation like "get_transactions_in" in your Transaction_in model

Laravel Eloquent: 3 table relationship

I'm new to Laravel-eloquent, I would like to translate this SQL to Eloquent mode:
select
fl.id, fut.id, fut.firebase_topic_id, ft.id, fl.created_at
from
firebase_logs fl,
firebase_user_topics fut,
firebase_topics ft
where
fl.id = fut.firebase_log_id
and
fut.firebase_topic_id = ft.id
and
fl.created_at between '2019-01-09 16:33:39' and '2019-01-09 16:33:41'
and
ft.id = 1
order by fl.created_at asc
Where:
Firebase_logs.id (1) -> Firebase_user_topics.firebase_log_id (N)
and
Firenase_user_topics.firebase_topic_id (N) -> Firebase_topics.id (1)
FirebaseLog.php:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class FirebaseLog extends Model
{
public $incrementing = false;
protected $primaryKey = 'id';
public function user_topics() {
//return $this->hasManyThrough(FirebaseTopics::class, FirebaseUserTopics::class);
return $this->hasMany(FirebaseUserTopics::class);
}
}
FirebaseUserTopics.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class FirebaseUserTopics extends Model
{
protected $table = 'firebase_user_topics';
public function log()
{
return $this->belongsTo(FirebaseLog::class);
}
public function topic()
{
return $this->belongsTo(FirebaseTopics::class);
}
}
FirebaseTopics.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class FirebaseTopics extends Model
{
protected $table = 'firebase_topics';
public function user_topics()
{
return $this->hasMany(FirebaseUserTopics, 'firebase_user_topics');
}
}
My Controller, works fine with this:
$a = FirebaseLog::with('user_topics')->whereBetween('created_at', array('2019-01-09 16:33:39', '2019-01-09 16:33:41'))->get();
return $a;
But I don't know how to connect to FirebaseTopics to continue building the code, some help will be appreciated.
EDITED ANSWER!
The solution of your problem is use the hasOne relation instead of belongsTo in your FirebaseUserTopics model. It must be following;
public function topic()
{
return $this->hasOne(FirebaseTopics::class, 'id', 'firebase_topic_id');
}
Because your FirebaseTopics model has not a relation with FirebaseUserTopics model. The "belongsTo" (that uses to make reverse a relation) search firebase_topic_id field in the firebase_topics table but this field has no in the firebase_topics table. That's why, you must be make to relation directly, not reverse.

Multiple belongsTo Eloquent

I have 3 models objects, namely: Categories, Category_products & Products
Categories:
<?php
class Categories extends Model
{
protected $table = 'categories';
public function product_ids() {
return $this->hasMany("app\Models\categories\Category_products", "category_id", "id");
}
?>
Category_products:
<?php
class Category_products extends Model
{
protected $table = 'category_products';
public function product_ids(){
return $this->belongsTo('app\Models\categories\Category');
}
public function products(){
return $this->hasOne("app\Models\Product", "id", "product_id");
}
}
?>
And Product:
<?php
class Product extends Model {
protected $table = 'products';
public function product(){
return $this->belongsTo("app\Models\categories\Category_products");
}
?>
Now in my CategoryController I do:
$this->data["products"] = Categories::find($id)->product_ids()->products()->get();
But now I get an error :
Call to undefined method Illuminate\Database\Query\Builder::products()
How can I do this the right way ?
OK, I'm going to try.
I guess you missed something when reading the Laravel documentation.
You don't have to create the category_products Models because it's your pivot table between your Categories and your Product.
"Normally", you should have something like this :
Products :
. id
. name
Categories :
. id
. name
category_product (alphabetically ordered name)
. product_id
. category_id
And your Models:
class Category extends \Eloquent {
public function products()
{
return $this->belongsToMany('namespace\to\your\model\Product');
}
}
class Product extends \Eloquent {
public function categories()
{
return $this->belongsToMany('namespace\to\your\model\Category');
}
}
Then you can do the following :
$this->data["products"] = Category::find($id)->products;
or
$this->data["products"] = Category::find($id)->products()->get();
Laravel will take care to call the pivot table for you.
It's not common to name your class with a plural, get used to name your class with their singular
And see also : http://laravel.com/docs/5.0/eloquent#many-to-many

Getting foreign tables value laravel

here is an example
Table Structure
Game
--id
--game
Posts
--id
--game_id
--post_text
class Posts extends Eloquent {
protected $primaryKey = 'id';
protected $table = 'posts';
public function games() {
return $this->hasOne('games','id');
}
}
class Games extends Eloquent {
protected $primaryKey = 'id';
protected $table = 'games';
public function posts() {
return $this->belongsTo('posts','game_id');
}
}
I need to get the game name of a certain post. How can I get it using eloquent?
here is my initial code
echo $post->games['game'];
but I get the wrong data.
The way it queries is this.
'query' => string 'select * from `games` where `games`.`id` = ? limit 1' (length=52)
'bindings' =>
array (size=1)
0 => int 5
Firstly Eloquent model names are not plural, so by default they should be Game and Post.
Secondly relationship return values must be changed. In hasOne and belongsTo you will need to use model class names like below. I also left out some optional code which is not required for the code to work.
class Post extends Eloquent {
public function game() {
return $this->hasOne('Game');
}
}
class Game extends Eloquent {
public function post() {
return $this->belongsTo('Post');
}
}
Now you can get the game name by $post->game->name

Laravel Relationship 1-2-1

I've a tables what looks that:
Users:
id | username | password | ...
Users_Services
id | user_id | service_id | active | paidTo
And Services:
id | title | description | type | price | active
I want get services of current user with all data about it from another table, so my relationship should looks:
I don't know how can I do that on "User_Services" class, in Controller I've:
$services = User::find( Auth::user()->id )->services;
User class:
public function services() {
return $this->hasMany('User_Services');
}
And Services class:
public function user_services()
{
return $this->hasManyThrough('User_Services', 'User', 'service_id');
}
Now how about User_Services class, how can I do that relationship?
From User class you can declare both relationships.
Edit: I got confused by the arrows: If the relation is 1-N_1-N
class User extends Eloquent {
public function services()
{
return $this->hasManyThrough('Services', 'Users_services');
}
public function usersServices()
{
return $this->hasMany('Users_services');
}
}
If it is many to many 1-N_N-1
class User extends Eloquent {
public function services()
{
return $this->belognsToMany('Services', 'Users_services');
}
}
class Services extends Eloquent {
public function services()
{
return $this->belognsToMany('Users', 'Users_services');
}
}
I believe you are actually looking for a many-to-many relationship which in Laravel is going to be defined with the belongsToMany() function. You can set those up like so...
class User extends Eloquent {
public function services()
{
return $this->belongsToMany('Service')->withPivot('active', 'paidTo');
}
}
class Service extends Eloquent {
public function users()
{
return $this->belongsToMany('User');
}
}
The withPivot() part is grabbing those additional columns you have on your User_services table.
Now getting a user's services should be very easy and can be done like so...
$services = Auth::user()->with('services');
foreach($services as $service) {
echo $service->description;
// If you need to display information from the pivot table, that can be done like so.
echo $service->pivot->paidTo;
}

Categories