Find result with hasmany relationship in laravel - php

I am just starts a project in laravel and this is new environment for me. I am familiar with PHP and also models relationship. But the laravel structure is little bit complex for starting.
So the problem is I have a question and Course table, A single question may have more then one course so i created one more table which hold course id and question id.
Question Model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Question extends Model{
protected $primaryKey = "id";
public function courses(){
return $this->hasMany('App\Models\CourseQuestion');
}
}
Course model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Course extends Model {
protected $primaryKey = "id";
public function questions(){
return $this->hasOne('App\Models\CourseQuestion');
}
}
And last courseQuestion model
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class CourseQuestion extends Model {
protected $primaryKey = "id";
public function questions(){
return $this->hasOne('App\Models\Question');
}
public function courses(){
return $this->hasMany('App\Models\Course');
}
}
And my controller where i getting result -
class IndexController extends BaseController {
public function index(){
$user = Question::with('user','courses','branches')->find(100);
echo "<pre>";
print_r($user); die;
}
}
So the courses return only id of course and questions which store in third table but i want the course name respective id. Please help
Thanks.

namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Question extends Model
{
protected $primaryKey = "id";
public function courses()
{
return $this->hasMany('App\Models\CourseQuestion', 'course_question_id', 'id')
->select('id', 'name');
}
}

Related

Laravel RelationShips eloquent Laravel with ( 5 tables )

I have 5 tables
Products
-- Categories
--- SubCategories
---- Marks
----- Suppliers
I want to know how to make relationship
I have Product Model structure with :
namespace App\Models\Products;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
use HasFactory;
protected $fillable = [.... ];
public function categorie(){
return $this->belongTo(categories::class);
}
public function sub_categorie(){
return $this->belongTo(sub_categorie::class);
}
public function marks(){
return $this->belongTo(marks::class);
}
public function suppliers(){
return $this->belongTo(suppliers::class);
}
}
i want to know if it's correct ?
Another Question how would be looks other Model relationships such Suppliers, Categories, SubCategories ...
It depends on the cardinality and the foreign_keys that are involved.
Products
-- Categories
--- SubCategories
---- Marks
----- Suppliers
The context that you gave me, I'm guessing that each table depends on the previous one as showed in the context that you gave. If so, then you can do the following:
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Suppliers extends Model
{
protected $fillable = [.... ];
public function mark()
{
return $this->belongsTo(Mark::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Marks extends Model
{
protected $fillable = [.... ];
public function subCategorie()
{
return $this->belongsTo(SubCategorie::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class SubCategory extends Model
{
protected $fillable = [.... ];
public function categorie()
{
return $this->belongsTo(Categorie::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Categorie extends Model
{
protected $fillable = [.... ];
public function categorie()
{
return $this->belongsTo(Product::class);
}
}
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Product extends Model
{
protected $fillable = [.... ];
}
For more in depht inormation, you can consult the section about relationshipts on laravel docs: https://laravel.com/docs/8.x/eloquent-relationships.
Please use the correct nomeclature of relationship's, instead of "categorie" write "category" in the function name, with that laravel will automaticaly recognise the foreign key.
Example:
public function category(){
return $this->belongTo(categories::class);
}
public function sub_category(){
return $this->belongTo(SubCategory::class);
}
public function mark(){
return $this->belongTo(Mark::class);
}
public function supplier(){
return $this->belongTo(Supplier::class);
}
Show me your models folder please if you have any problem .

Why belongsToMany returns null in Laravel 5.4?

I'm trying to implement a belongsToMany relationship, where I need to list products and right after the name of the same, the relationship is made between 3 tables, order, description and order_product.
As you can realize the field appears empty.
This is my belongsToMany relation:
Description Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
use App\Order;
class Description extends Model
{
protected $table = 'erp_product_description';
protected $primaryKey = 'erp_productid';
protected $fillable = ['erp_name'];
public $timestamps = false;
public function product()
{
return $this->belongsTo('App\Product', 'erp_productid','erp_productid');
}
public function order()
{
return $this->belongsToMany('App\Order', 'erp_order_product', 'erp_productid', 'erp_createdid');
}
}
Order Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Order extends Model
{
protected $table = 'erp_order';
protected $fillable = ['erp_createdid'];
public function description()
{
return $this->belongsToMany('App\Description', 'erp_order_product', 'erp_createdid', 'erp_productid');
}
}
I used the Laravel 'DebugBar' plugin to see which query is running and returned this:
select `erp_product_description`.*, `erp_order_product`.`erp_createdid` as `pivot_erp_createdid`, `erp_order_product`.`erp_productid` as `pivot_erp_productid` from `erp_product_description` inner join `erp_order_product` on `erp_product_description`.`erp_productid` = `erp_order_product`.`erp_productid` where `erp_order_product`.`erp_createdid` is null
Why my query received null in value? Any suggestion?

Laravel 5.4 call a model function on an instance returned by another laravel model function

I have 3 tables and the corresponding models which are connected as shown below:
Telephones.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Telephones extends Model {
protected $table = 'telephones';
protected $primaryKey = 'telephone_id';
public function UserTelephone() {
return $this->hasOne('App\Models\Users','user_id','user_id');
}
}
Addresses.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Addresses extends Model {
protected $table = 'addresses';
protected $primaryKey = 'address_id';
public function UserAddress() {
return $this ->hasOne('App\Models\Users','address_id','address_id');
}
}
Users.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model {
protected $table = 'users';
protected $primaryKey = 'user_id';
}
In my view I want to connect user's telephone with user's address so I do the following:
<?php $user_telephone = $telephone->UserTelephone()->first();
$address = $user_telephone->UserAddress()->first();
?>
but it fails with error:
BadMethodCallException in Builder.php line xxxx:
Call to undefined method
Illuminate\Database\Query\Builder::UserAddress()
Any ideas how I could solve it?
On your telephones and address model, I would say to use Belongs to instead of Has One.
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\Users;
class Addresses extends Model {
protected $table = 'addresses';
protected $primaryKey = 'address_id';
public function UserAddress() {
return $this->belongsTo(Users::class);
}
}
class Telephones extends Model {
protected $table = 'telephones';
protected $primaryKey = 'telephone_id';
public function UserTelephone() {
return $this->belongsTo(Users::class);
}
}
From https://laravel.com/docs/5.4/eloquent-relationships#one-to-one
Defining The Inverse Of The Relationship
The reason your case doesn't work on user address is because you may not have the address_id field on your user model.
return $this->hasOne('App\Models\Users','id','user_id');
You are creating a relationship so therefore you need to let it know how they're connected. I would suggest read more about relationships: https://laravel.com/docs/5.4/eloquent-relationships
Try to call your model functions like this :
$user_telephone = $telephone->UserTelephone;
$address = $user_telephone->UserAddress;
this will be okay only if $telephone its a Telephone model
EDIT
Your error is in the place you declare you model relationship
change this:
return $this->hasOne('App\Models\Users','user_id','user_id');
to this
return $this->hasOne(Users::class,'user_id','user_id');
and the same with your other function
*make sure what is your models name.. most of the times is User
Telephone Model :
public function UserTelephone() {
return $this->belongsTo('App\Models\Users','user_id','user_id');
}
Address Model :
public function UserAddress() {
return $this->belongsTo('App\Models\Users','address_id','address_id');
}
Controller :
$telephone =Telephone::find(1); //get first telephone
$user_telephone = $telephone->UserTelephone; // get User
$address = $user_telephoneObject->UserAddress; //get Address Of the user
Finally I managed to solve it, the issue was that I was trying to call a model's function on the wrong object.
My goal was to get the address when user was known. To be more specific I had the following relationship: telephone->user->address. As you could see to the initial posted code, I declared 2 functions, UserTelephone and UserAddress. Then I called UserTelephone on a telephone object and UserAddress on a recipient object. This was the reason that my code failed. Had to create a new function on Users model to be able to get the address when user was know. Working code posted below:
Telephones.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Telephones extends Model {
protected $table = 'telephones';
protected $primaryKey = 'telephone_id';
public function UserTelephone() {
return $this->belongsTo('App\Models\Users','user_id','user_id');
}
}
Addresses.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Addresses extends Model {
protected $table = 'addresses';
protected $primaryKey = 'address_id';
public function UserAddress() {
return $this ->belongsTo('App\Models\Users','address_id','address_id');
}
}
Users.php:
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
class Users extends Model {
protected $table = 'users';
protected $primaryKey = 'user_id';
public function Address() {
return $this->hasOne('App\Models\Addresses','address_id','address_id');
}
}
In my view:
<?php $address = $telephone->UserTelephone->Address()->first();?>

Laravel Eloquent model returns null for one to many relation

I am not sure what is going on here. I am getting returns of null despite having the info in the database.
Stimuli Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Stimuli extends Model
{
protected $table = 'stimuli';
public $timestamps = false;
/**
* Get the details associated with the stimulus
*/
public function info()
{
return $this->hasMany('App\StimuliInfo', 'attribute', 'value');
}
}
StimuliInfo Model
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class StimuliInfo extends Model
{
/**
* Get the stimuli associated with the detailss
*/
protected $table = 'stimuli_info';
public $timestamps = false;
public function info()
{
return $this->belongsTo(Stimuli::class);
}
}
Controller
<?php
namespace App\Http\Controllers;
use App\User;
use App\Http\Controllers\Controller;
use Illuminate\Support\Facades\DB;
use App;
use Illuminate\Http\Requests;
class Labels extends Controller
{
public function index()
{
}
public function objects()
{
$stimulus = App\Stimuli::with('info')->get();
foreach ($stimulus as $stim)
{
$stimuli[] = $stim->stimulus_id;
}
return $stimuli;
shuffle($stimuli);
return view('label/objects')->with(compact('stimuli'));
}
}
Okay, so here is a test controller. For some reason, I am getting a null output for every data point. Which is odd as I can see in the DB that there is data there which is not null.
I am wondering whether I am doing something fishy in the model that is not right outputting this data.
Any help would be greatly appreciated - I am at a loss for this process

Laravel relationships on a table with two types of flags

I have two tables
products and users
Both of this objects has images associated with it in a table
images
The schema for the images table is
id | image_id | resource_id | flag
1 | 567575 | 1 | user
2 | 423423 | 1 | product
Based on this flag i am identifying whether its a users image or whether its a products image.
If I need to eager load a users image how do it do it?
User model
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'users';
protected $primaryKey = 'users_id';
public function images()
{
return $this->hasMany('App\Entities\Image','resource_id');
}
}
Product model
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Product extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'products';
protected $primaryKey = 'products_id';
public function images()
{
return $this->hasMany('App\Entities\Image','resource_id');
}
}
images model
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Image extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'images';
protected $primaryKey = 'images_id';
public function products()
{
return $this->hasOne('App\Entities\Product','products_id');
}
public function users()
{
return $this->hasOne('App\Entities\User','users_id');
}
}
Is there a way I can pass a flag in the relationship function of images() so that it will fetch the record based on the flags?
Please help out.
You can try this adding a conditional inside your images() method:
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class User extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'users';
protected $primaryKey = 'users_id';
public function images($filtered=false)
{
if ($filtered) {
return $this->hasMany('App\Entities\Image','resource_id')->where('flag','user');
}
return $this->hasMany('App\Entities\Image','resource_id');
}
}
and try the same logic to your Product model
Change your Image model to:
<?php
namespace App\Entities;
use Illuminate\Database\Eloquent\Model;
class Image extends Model implements Transformable
{
use TransformableTrait;
protected $table = 'images';
protected $primaryKey = 'images_id';
public function product()
{
return $this->belongsTo('App\Entities\Product', 'products_id', 'resource_id');
}
public function user()
{
return $this->belongsTo('App\Entities\User', 'users_id', 'resource_id');
}
}
try with this way :
$user_id = 1;
$my_image= User::find($user_id)->images()->where('flag', '=', 'user')->first();

Categories