PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label relationship. Show all posts
Showing posts with label relationship. Show all posts

Wednesday, November 16, 2022

[FIXED] how to retrieve limited number of related model and sort collection by related model in laravel?

 November 16, 2022     laravel, laravel-6, relationship     No comments   

Issue

I have 3 model Shop model, Product model, Picture model

I want to retrieve a collection of shops with last 3 Product model with their pictures and sort my collection based on newest product. I tried leftjoint and joint in laravel 6 to be able to sort the result but i get all shops`product (i only need last 3 product for each shop),

when I use joint I cant retrieve product pictures I also have tried “with” method in laravel , I couldnt sort the result based on product.creatred_at and also i get all related product in this method too.(as i mentioned i need the last 3 product)

class Shop extends Model
{
    public function products()
    {
        return $this->hasMany('App\Product');
    }
}

class Product extends Model
{

    public function shop()
    {
        return $this->belongsTo('App\Shop');
    }

    public function pictures()
    {
        return $this->morphMany('App\hPicture', 'pictureable');
    }

}


Shop::select('shops.*', 'products.id', 'products.shop_id', 'products.name as pname', 'products.user_id', 'products.code', 'products.price')
            ->with(['pictures', 'products.pictures'])
            ->leftjoin('products', function ($leftJoin) {
                $leftJoin->on('shops.id', '=', 'products.shop_id');
            });
            $dataList = $dataList->orderBy($field, $order);
            $dataList = $dataList->paginate(5)->appends(['sortField' => $field, 'sortOrder' => $order]);

the table layout for product and shop model is:

 Schema::create('shops', function (Blueprint $table) {
        $table->increments('id');
        $table->string('name');
        $table->string('slug');
        $table->string('phone')->nullable();
        $table->string('address')->nullable();  
        $table->timestamps();
        $table->string('description')->nullable();
        $table->uuid('uuid');
    });
 Schema::create('products', function (Blueprint $table) {
            $table->increments('id');
            $table->integer('shop_id')->unsigned();
            $table->foreign('shop_id')->references('id')->on('shops');
            $table->string('name');
            $table->string('code');
            $table->string('slug');
            $table->integer('price');
            $table->uuid('uuid');
            $table->timestamps();
        });

Solution

There are only 2 ways of resolving this:

  1. Either you pull in all products, and trim them in the end(advisable only if not too many products per shop):
$shops = Shop::with(['products' => function($subQuery) { 
    $subQuery
        ->with('pictures') //Running in scope of product, also load each product's pictures
        ->orderBy('created_at', 'desc');
}])
->get();
foreach ($shops as $shop) {
   $shop->setRelation('products', $shop->products->take(3));
}

NOTE:

You will load every single product that is linked to the shops you load. You could get memory issues with this.

  1. Take only what you need, but introduce a n+1 query issue(advisable only with small quantities of $shops:
$shops = Shop::get();
foreach ($shops as $shop) {
    $shop->load([
        'products' => function($query) {
            $query
                ->orderBy('created_at', 'desc')
                ->limit(3)
                ->get();
    }]);
}

NOTE:

N+1 query problem: You are performing a new query for each shop, so if you have a million shops, it will be a million extra queries.

EDIT: (answering comment question)

Q: How can i sort $shops based on their latest product created_at field?

$sortedShops = $shops->sortBy(function ($shop, $key) {
    return $shop->products->first()->created_at;
})->values()->all();

sortBy is called on the collection(not uery). It allows you to go over each element(in this case shops) and use each object. Please do note that this function will fail if you have no products linked to the shop.

The ->values()->all() at the end makes sure that when you convert your shops to json, you will create an array, and not an object in js.

Source: https://laravel.com/docs/7.x/collections#method-sortby

EDIT: (deleted original answer as it did not work)

  • Previous answer does not work, because limit(3) will limit the total amound of products loaded, in stead of 3 products per shop(my bad).


Answered By - Techno
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, November 15, 2022

[FIXED] Why my model can't see spatie permissions trait method on relationship subquery?

 November 15, 2022     eloquent, laravel, laravel-6, laravel-permission, relationship     No comments   

Issue

I use spatie/laravel-permissions composer package in my laravel projects. When I run this query:

$jobs = Job::whereIn('id', $ids)->whereHas('user', function ($query) {
    $query->hasRole('company');
})->get();

Return error message

Call to undefined method Illuminate\Database\Eloquent\Builder::hasRole()

How I can fix my problem in my case?


Solution

The hasRole-method is not a scope and can't be used on a Builder instance.

I think you should be able to use the role-scope in your application.

$jobs = Job::whereIn('id', $ids)->whereHas('user', function ($q) {
    return $q->role('company');
})->get();


Answered By - stefanzweifel
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, October 21, 2022

[FIXED] How to get datas from related tables in Phalcon?

 October 21, 2022     foreign-keys, has-many, phalcon, php, relationship     No comments   

Issue

I have exactly the same structure like in the phalcon models documentation: http://docs.phalconphp.com/en/latest/_images/eer-1.png

In the models I implemented the following hasmany and belongsto lines:

Robots model:

class Robots extends \Phalcon\Mvc\Model
{
    public $id;
    public $name;
    public function initialize(){
        $this->hasMany("id", "RobotsParts", "robots_id");
    }
}

Parts model:

class Parts extends \Phalcon\Mvc\Model
{
    public $id;
    public $name;
    public function initialize(){
        $this->hasMany("id", "RobotsParts", "parts_id");
    }
}

RobotParts model:

class RobotsParts extends \Phalcon\Mvc\Model
{
    public $id;
    public $robots_id;
    public $parts_id;
    public function initialize(){
        $this->belongsTo("robots_id", "Robots", "id");
        $this->belongsTo("parts_id", "Parts", "id");
    }
} 

At this point I was hoping to get all the data by calling RobotParts::find(), but I can see only the id's. For debuging I dumped, but find only the ids:(

$rp = RobotParts::find()->toArray();
var_dump($rp);

I would like to get something like this as result:

array (size=1)
  0 => 
    array (size=7)
      'id' => int '1' (length=1)
      'robots_id' => int '4' (length=1)
          'name'  => string 'r2d2' (length=4)
          'type'  => string 'droid' (length=5)
          'year'  => int '2184' (length=4)
      'parts_id' => int '4' (length=1)
          'name'  => string 'wheel' (length=5)

Solution

var_dump() does not contains the related tables, needed to reference to it from view like:

robots.RobotParts.name


Answered By - b4l4zs
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, July 26, 2022

[FIXED] How to get all records(related and non related) of Laravel belongsTo relationship?

 July 26, 2022     belongs-to, eloquent, laravel, relationship     No comments   

Issue

How can I get all the records from the relationship? I mean not only the related records, but also the rest.

Let's say I have a post which belongs to some category. If I want to change the category of this post I need a list of all available categories. Can I get this list from the relationship?

The Post model:

class Post extends Model
{
    public function category()
    {
        return $this->belongsTo('App\Category');
    }
}

The Category model:

namespace App;

use Illuminate\Database\Eloquent\Model;

class Category extends Model
{
    public function posts()
    {
        return $this->hasMany('App\Post');
    }
}

In the PostsController I tried:

$postModel->category->find('all'); // Returns null
$postModel->category->all(); // Returns only the related categories

I know I can simply use the Category model in the PostsController, but I prefer to do it using the relationship.


Solution

If you feel you must use the relationship to get to the other model you could try:

$categories = $post->category()->getRelated()->get();


Answered By - lagbox
Answer Checked By - Terry (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, July 9, 2022

[FIXED] How do I rename relationships in Neo4j?

 July 09, 2022     cypher, keyword, neo4j, relationship, rename     No comments   

Issue

I realized only after importing a ton of nodes that I had created relationships called START, which is a reserved keyword. Querying the DB through the Cypher console hence always complains about the reserved keywords:

SyntaxException: reserved keyword "start n=node(0) match n<-[:START]-r return count(r)"

The only workaround that comes to mind is creating new copy relationships with a different name and then deleting the old ones.

Is there an easy way to rename all of these relationships or some way to escape reserved keywords in Cypher?


Solution

You are right. You cannot rename an already existing relationship. You'd have to run through all relationships, create the new one in parallel (including all properties) and then remove the old one.

You may also want to consider quoting the reserved word START in your cypher queries with backticks and leave the relationships as they are:

start n=node(0) match n<-[:`START`]-r return count(r)


Answered By - James
Answer Checked By - Pedro (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, June 28, 2022

[FIXED] How to create relationships in according to date order in Neo4j

 June 28, 2022     graph, graph-databases, neo4j, relationship     No comments   

Issue

I have many nodes and zero relationships. How can I create relationships that join the same person following date order? (the picture represents the situation I would like to obtain) See Image


Solution

If you have apoc, this is would be my approach.

MATCH (p:Person)
WITH p order by p.date
WITH p.name as personName, collect(p) as personList
WITH apoc.coll.pairsMin(personList) as pairs
UNWIND pairs as pair
WITH pair[0] as p0, pair[1] as p1
MERGE (p0)-[:SAME_PERSON]->(p1)


Answered By - Nathan Smith
Answer Checked By - Mildred Charles (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, May 21, 2022

What Is the Relationship Between JavaScript and PHP?

 May 21, 2022     and, between, javascript, PHP?, relationship, the, What     No comments   

PHP and JavaScript are complementary

PHP and JavaScript are complementary. They are both used to create web pages and interact with databases, but they have different places in the process.

PHP is a server-side language, meaning it runs on the server. You can think of it like your computer's operating system: PHP handles all the logic and processing, while JavaScript exists to make things look pretty for users. When you visit a website that has lots of interactive elements—like buttons, menus or forms—that's where you'll see JavaScript in use.

PHP Is the Server-Side Solution

PHP is a server-side scripting language, which means that it's used to create dynamic web pages and store data in databases. If you've ever seen a Web page with the green "This site is using [insert favorite CMS here]" tag at the bottom, chances are good that PHP was involved somehow.

PHP can also be used to create simple forms and process form data via AJAX without having to write too much JavaScript yourself. While this may seem more like an annoyance than anything else at first glance, being able to use PHP makes it possible for developers who aren't well versed in JavaScript or NodeJS (which we'll discuss later)

PHP is not just for websites; it has other uses too: some people use it as an alternative to ASP classic and ASP .Net CORE MVC frameworks on their servers; others use it as part of their development process when building their own software packages from scratch or even reusing existing open source projects (see WordPress).

JavaScript Is the Client-Side Solution

  • JavaScript is a client-side solution.

  • JavaScript is a scripting language.

  • JavaScript is a scripting language that runs in the browser and adds interactivity to web pages, which is why it's often called "the glue of the internet."

How PHP and JavaScript Work Well Together

PHP is used to create dynamic web pages. JavaScript is used to create dynamic web pages. PHP is used to create the server-side code and JavaScript is used to create the client-side code. So, if you're building a website where you need both client-side and server-side code, then it makes sense that they work well together.

Both these languages are used in web development to create dynamic websites.

Both these languages are used in web development to create dynamic websites. PHP is a server-side language and JavaScript is a client-side language.

PHP and JavaScript are complementary technologies that enable the creation of interactive web pages. PHP scripts execute on the server, while JavaScript code runs on the browser; therefore, they are executed at different times and places. They allow you to create more dynamic and interactive websites by gathering data from users without having them reload the page every time they want to send information back to your website or application.

Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Wednesday, March 16, 2022

[FIXED] How to do association between a table with an ID and another table using the same ID but twice

 March 16, 2022     associations, cakephp, relationship, self     No comments   

Issue

In cakephp, I have a table users with primary key ID and another table friends with 2 foreign keys user_id, friend_id, both indexed to the same primary key in users table. I wanna know, how the heck do I connect them in the model?

Thanks!


Solution

You can use table alias.

    $this->belongsToMany('Friends', [
        'className' => 'Users',
        'foreignKey' => 'friend_id',
        'targetForeignKey' => 'user_id',
        'joinTable' => 'users_friends',
    ]);


Answered By - Kani
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, March 8, 2022

[FIXED] Yii Define relation to same model through other model

 March 08, 2022     php, relationship, yii     No comments   

Issue

In my Yii app I have 2 models, Profiles and Groups. Each profile belongs to a Group defined by Profiles.GroupID that is a FK to Groups.GroupID. Also, each Group has a manager (Group.ManagerID) which is basically another profile (therefore, it references a user_id in the table Users).

In model Profiles I would like to define a relation so that, for a given Profile I can easily retrieve the Manager.

Below is some sample data from the two tables that represent the 2 models Profiles, Groups:

Table Profiles
user_id  firstname    lastname     group_id
-------  -----------  ----------   -------  
1        John         Doe          100  
2        Walter       White        200  
3        Gus          Fring        100  
4        Biggie       Smalls       200  


Table: Groups
group_id   manager_id
-------    ---------
100        2
200        4

Any suggestions would be appreciated.


Solution

You can use relations, you must create two "BELONGS_TO" and "HAS_ONE" relations one in Profiles model and second in Groups model:

for example in Profiles:

public function relations() {
    'group' => ...
}

in Groups:

public function relations() {
    'manager' => ...
}

and than you can get manager of concrete user like this $user->group->manager.

But in this case generates query with two JOINs, which can be slow if your tables are big.

Or you can use only one relation (for getting user group) and one more query for getting manager: In Profiles model create public variable $manager and add it in your model rules (f.e in search)

public $manager = null;

and override method afterFind:

public function afterFind() {
    $this->manager = self::model()->findByAttributes('user_id' => $this->group->manager_id);
    return parent::afterFind()
}

EDITED

If you use the first method (two relations), you can override Sort object of your DataProvider (f.e. in method "sort" of your model):

public function search() {
        $criteria = new CDbCriteria;
        $sort = new CSort;
        $sort->defaultOrder = 'someField ASC';
        $sort->attributes = array(
            '*',
            'managerLastname' => array(
                'ASC' => 'group.manager.lastname ASC',
                'DESC' => 'group.manager.lastname DESC',
            )
        );
        // .....other criterias
        $criteria->compare('managerLastname', $this->group->manager->lastname, true); // for filtering

        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'sort' => $sort
        ));
    }

and in CGgridView columns add/change column

array(
    'name'=>'managerLastname',
    'value'=>'$data->group->manager->lastName'
) // be sure that each user has manager

and add also public property managerLastname in your model.

Thanks.



Answered By - Taron Saribekyan
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Laravel Ajax fetch data one to many relationship

 March 08, 2022     ajax, database, laravel, one-to-many, relationship     No comments   

Issue

I'm trying to fetch data from one to many relationship via Ajax Call.

My RestaurantOffer_table table:

id | restaurant_offer_id | tableName | fromNr | toNr 
-----------------------------------------------------
1  | 1                   | table1    | 1      | 4
-----------------------------------------------------
2  | 1                   | table2    | 5      | 10

Now, I have to fetch these data from this table.

Model RestaurantOffer.php

class RestaurantOffer extends Model
{
     protected $guarded = [];
     public function restaurant_offer_table()
    {
        return $this->hasMany(RestaurantOffer_table::class);
    }
}

Model RestaurantOffer_table.php

class RestaurantOffer_table extends Model
{
    protected $guarded = [];
    public function restaurantoffer()
    {
        return $this->belongsTo(RestaurantOffer::class);
    }
}

Controller RestaurantOffersController.php

function fetchdata(Request $request)
{
    $id = $request->input('id');
    $data = RestaurantOffer::find($id);

    $output = array(
        'monthlySum'    =>  $data->monthlySum,
        'userProfitPercentage'    =>  $data->userProfitPercentage,
        ....................... 
    );

    if($request->ajax()) {
      echo json_encode($output);
  }  
       
}

In this controller, all my data from RestaurantOffer model are fetching as well, but how to fetch data also from RestaurantOffer_table model using the same function in controller.

View Ajax function:

$(document).on('click', '.edit', function(){
var id = $(this).attr("id");
var image_index= $(this).attr('data-index');
$('#form_output').html('');
$.ajax({
    url: "{{route('restaurantOffers.fetchdata')}}",
    method: 'get',
    data: {id:id},
    dataType: 'json',
    success:function(data)
    {                   
        $('#getMonthlySum').val(data.monthlySum);
        $('#userProfitPercentage').val(data.userProfitPercentage);
        $.........
         
        $('#contract_id').val(id);                
        $('#editContract').modal('show');
        $('#action').val('Speichern');
        $('.modal-title').text('Daten aktualisieren');
        $('#button_action').val('update');
        
    }
});

So, the question is, how to fetch data from RestaurantOffer_table for each row of RestaurantOffer via Ajax call. e.g

Restaurant 1 -> table1 | 1 | 4
                table2 | 5 | 10

Thank you in advance.


Solution

You have defined the Relation in model. Thats good. But did not used while fetching in controller.

You have mention the relation function in with() method while doing model query like below

$data = RestaurantOffer::with('restaurant_offer_table')->where('id',$id)->first();

It will call eagerloading method in laravel.

But you can also use that relation method after the elequent query.

$data = RestaurantOffer::find($id);
$data->restaurant_offer_table; // like this.

But it is not eagerloaded and you can not use this function in js file so you have to eager load the data.



Answered By - Apurv Bhavsar
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, February 28, 2022

[FIXED] How make eloquent laravel relathionship migration with the same table?

 February 28, 2022     database, eloquent, laravel, migration, relationship     No comments   

Issue

if instead of having a users table where one user can follow many users. I would have a cows table where each cow has a single father and a single mother, where the parents can have many children. do I require an external table to store that or can I just add in my cows table the fields cow_father_id and cow_mother_id? -referring to making 2 eloquent relationships of cows table with same cows table and what this migration would look like?


Solution

You could do this. I've tested as well.

Migration

Schema::create('cows', function (Blueprint $table) {
    $table->id();
    $table->string('name');
    $table->integer('father_id')->nullable();
    $table->integer('mother_id')->nullable();
    $table->timestamps();
});

Model

class Cow extends Model
{
    use HasFactory;

    public function father()
    {
        return $this->belongsTo(self::class, 'father_id');
    }

    public function mother()
    {
        return $this->belongsTo(self::class, 'mother_id');
    }

    public function children()
    {
        return $this->hasMany(self::class, 'father_id')->orWhere('mother_id', $this->id);
    }
}


Answered By - sithuaung
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 20, 2022

[FIXED] Set limit to eloquent relationship

 February 20, 2022     eloquent, laravel-5, php, relationship     No comments   

Issue

This is my query.

$helpCategoryList = HelpCategory::where('is_active', 1)
                               ->with(['helps' => function($query) {
            $query->with(['users'])
                  ->withcount(['helpComments','helpResponse','helpVotes'])
                  ->limit(5);}])
           ->orderBy('created_at', 'asc')
           ->get()
           ->toArray();

It gives totally 5 records from helps table,but i need each category 5 records of help details. So each category has many helps.


Solution

it's bit late but try my solution for once I hope it will work

$helpCategoryList = HelpCategory::where('is_active', 1)
                            ->with('helps')->whereHas('helps',function($query) {
                                    $query->with(['users'])
                                    ->withcount(['helpComments','helpResponse','helpVotes'])
                                      ->take(5);})
                            ->orderBy('created_at', 'asc')
                            ->get()
                            ->toArray();


Answered By - Mr. Pyramid
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Monday, February 7, 2022

[FIXED] How to create a self BelongsToMany relation in CakePHP 3

 February 07, 2022     cakephp, cakephp-3.0, database-design, relationship     No comments   

Issue

I have a database with a table "projekte" (german word for projects). Some of the projects have a relation to eachother. So i would like to have a BTM relation.

I created a joinTable "projektverbindungen" with the following fields:

projekt_id
nebenprojekt_id

I found a similar question here: BelongstoMany relationship between a table and itself and i tried the answer of ndm, but without success.

Here is my ProjekteTable.php

class ProjekteTable extends Table {
  public function initialize(array $config)
  {
    parent::initialize($config);

    $this->setTable('projekte');
    $this->setDisplayField('name');
    $this->setPrimaryKey('id');

    $this->hasOne('Projekteigenschaften', [
      'foreignKey' => 'projekt_id',
      'dependent' => true,
    ]);
    $this->belongsToMany('Projekte', [
      'foreignKey' => 'projekt_id',
      'targetForeignKey' => 'nebenprojekt_id',
      'joinTable' => 'projektverbindungen',
    ]);
  }
}

Here ist my template (add.ctp)

<?php
echo $this->Form->create($projekt);
echo $this->Form->control('name', ['class' => 'form-control']);
echo $this->Form->control('projekteigenschaft.projektverantwortlich');
echo $this->Form->control('projekteigenschaft.beschreibung');
echo $this->Form->control('projekte._ids', ['options' => $projekte, 'multiple' => true]);
echo $this->Form->button(__('Submit'));
echo $this->Form->end();
?>

The first step, saving a project with a related project works as expected. The id of the created project was saved as projektverbindungen.projekt_id and the id of the related project as projektverbindungen.nebenprojekt_id.

When i query a projekt without the relation to other projects like so:

$projekt = $this->Projekte->get($id, [
  'contain' => ['Projekteigenschaften']
]);

the query looks like this:

SELECT Projekte.id AS `Projekte__id`, Projekte.name AS `Projekte__name`, Projekteigenschaften.id AS `Projekteigenschaften__id`, Projekteigenschaften.projektverantwortlich AS `Projekteigenschaften__projektverantwortlich`, Projekteigenschaften.beschreibung AS `Projekteigenschaften__beschreibung`, Projekteigenschaften.projekt_id AS `Projekteigenschaften__projekt_id` FROM projekte Projekte LEFT JOIN projekteigenschaften Projekteigenschaften ON Projekte.id = (Projekteigenschaften.projekt_id) WHERE (Projekte.id = :c0 AND (Projekte.deleted) IS NULL)

And the debug of the result looks like:

"id": "6862279f-8134-401f-86ff-9278a3bfa5c3",
"name": "My Project",
"projekteigenschaft": {
    "id": "89d9e241-e700-4c31-9266-ee5717f2a0aa",
    "projektverantwortlich": "Blisginnis, Ralf",
    "beschreibung": ""
}

Everything works fine.

But when i add the projects to contain like so:

$projekt = $this->Projekte->get($id, [
  'contain' => ['Projekteigenschaften', 'Projekte']
]);

The query looks the same like above, but the entity looks a bit different:

"Projekteigenschaften": {
    "id": "89d9e241-e700-4c31-9266-ee5717f2a0aa",
    "projektverantwortlich": "Blisginnis, Ralf",
    "beschreibung": ""
}

Projekteigenschaften seems no longer to be a hasOne relation and "Projekte" gets totally ignored.

Anyone has an idea what i did wrong? Or should i prefer an other way of doing this?

edit after ndm´s comment

I tried defining the relationship like so:

$this->belongsToMany('Projektverbindungen', [
  'class' => 'Projekte',
  'foreignKey' => 'projekt_id',
  'targetForeignKey' => 'nebenprojekt_id',
  'joinTable' => 'projektverbindungen',
]);

and changed the add.ctp template like so:

echo $this->Form->control('projektverbindungen._ids', ['options' => $projekte, 'multiple' => true]);

But then it doesn´t save the relation.

I also tried to rename the joinTable to projekte_projekte. It didn´t seem to make any difference.

Then I tried to use the through-option, but the results of that were even worse. So I continued trying to find a solution with the method described above.

2nd edit

projekverbindungen ist accessible in Projekt.php:

protected $_accessible = [
  'name' => true,
  'projekteigenschaft' => true,
  'projekte' => true,
  'projektverbindungen' => true,
];

Debug of requestData:

[
  'name' => 'My Project',
  'projekteigenschaft' => [
    'projektverantwortlich' => 'John Doe',
    'beschreibung' => '',
  'projektverbindungen' => [
    '_ids' => [
      (int) 0 => '809031f2-4ecd-4dfb-82d5-2c911286dd21'
    ]
  ]
]

Debug of entity after patching:

object(App\Model\Entity\Projekt) {

  'name' => 'My Project',
  'projekteigenschaft' => object(App\Model\Entity\Projekteigenschaft) {

    'projektverantwortlich' => 'John Doe',
    'beschreibung' => '',
    '[new]' => true,
    '[accessible]' => [
        'projektverantwortlich' => true,
        'beschreibung' => true,
        'projekt_id' => true,
        'projekt' => true
    ],
    '[dirty]' => [
        'projektverantwortlich' => true,
        'beschreibung' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[hasErrors]' => false,
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Projekteigenschaften'

  },
  'projektverbindungen' => [],
  '[new]' => true,
  '[accessible]' => [
    'name' => true,
    'projekteigenschaft' => true,
    'projekte' => true,
    'projektverbindungen' => true
  ],
  '[dirty]' => [
    'name' => true,
    'projekteigenschaft' => true,
    'projektverbindungen' => true
  ],
  '[original]' => [],
  '[virtual]' => [],
  '[hasErrors]' => false,
  '[errors]' => [],
  '[invalid]' => [],
  '[repository]' => 'Projekte'
}

3rd edit

In my bootstrap.php i have this:

Inflector::rules('plural', [
  '/^(projekt)$/i' => '\1e',
  '/^(projekteigenschaft|projektverbindung)$/i' => '\1en',
]);
Inflector::rules('singular', [
  '/^(projekt)e$/i' => '\1',
  '/^(projekteigenschaft|projektverbindung)en$/i' => '\1',
]);

After your recommendation I additionally added propertyName to the definition of the association:

$this->belongsToMany('Projektverbindungen', [
  'class' => 'Projekte',
  'propertyName' => 'Projektverbindungen',
  'foreignKey' => 'projekt_id',
  'targetForeignKey' => 'nebenprojekt_id',
  'joinTable' => 'projektverbindungen',
]);

After that, the patched entity looks like this:

object(App\Model\Entity\Projekt) {

  'name' => 'My Project',
  'projekteigenschaft' => object(App\Model\Entity\Projekteigenschaft) {

    'projektverantwortlich' => 'John Doe',
    'beschreibung' => '',
    '[new]' => true,
    '[accessible]' => [
        'projektverantwortlich' => true,
        'beschreibung' => true,
        'projekt_id' => true,
        'projekt' => true
    ],
    '[dirty]' => [
        'projektverantwortlich' => true,
        'beschreibung' => true
    ],
    '[original]' => [],
    '[virtual]' => [],
    '[hasErrors]' => false,
    '[errors]' => [],
    '[invalid]' => [],
    '[repository]' => 'Projekteigenschaften'

  },
  'projektverbindungen' => [
    '_ids' => [
        (int) 0 => '1e28a3d1-c914-44be-b821-0e87d69cd95f'
    ]
  ],
  '[new]' => true,
  '[accessible]' => [
    'name' => true,
    'projekteigenschaft' => true,
    'projekte' => true,
    'projektverbindungen' => true
  ],
  '[dirty]' => [
    'name' => true,
    'projekteigenschaft' => true,
    'projektverbindungen' => true
  ],
  '[original]' => [],
  '[virtual]' => [],
  '[hasErrors]' => false,
  '[errors]' => [],
  '[invalid]' => [],
  '[repository]' => 'Projekte'
}

But still no new entry in the table "projektverbindungen"


Solution

The last suggestion of ndm made the trick. Now it works like expected. Thank you very much!

Here is the correct setup:

ProjekteTable.php

  $this->belongsToMany('Nebenprojekte', [
    'className' => 'Projekte',
    'foreignKey' => 'projekt_id',
    'targetForeignKey' => 'nebenprojekt_id',
    'joinTable' => 'projektverbindungen',
  ]);

Here I used the property class instead of className, that has been the biggest issue. Thats really embarrassing, because in the Cookbook is the correct name of that property: https://book.cakephp.org/3/en/orm/associations.html#belongstomany-associations

Nevertheless, perhaps anyone else makes the same mistake and this thread can help.

The second thing is not to use the jointable`s name as the name of the association.

The rest is just straight forward...

Making the association accessible in the Entity Class (Projekt.php):

protected $_accessible = [
  'name' => true,
  'projekteigenschaft' => true,
  'nebenprojekte' => true,
];

ProjekteController.php ("add" and "edit"):

public function add()
{
    $projekt = $this->Projekte->newEntity();
    if ($this->request->is('post')) {
        $projekt = $this->Projekte->patchEntity($projekt, $this->request->getData());
        if ($this->Projekte->save($projekt)) {
            $this->Flash->success(__('flash message'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('error message'));
    }

    $projekte = $this->Projekte->find('list');
    $this->set(compact('projekt', 'projekte'));
}

public function edit($id = null)
{
    $projekt = $this->Projekte->get($id, [
      'contain' => ['Projekteigenschaften', 'Nebenprojekte']
    ]);

    if ($this->request->is(['patch', 'post', 'put'])) {
        $projekt = $this->Projekte->patchEntity($projekt, $this->request->getData());
        if ($this->Projekte->save($projekt)) {
            $this->Flash->success(__('flash message'));

            return $this->redirect(['action' => 'index']);
        }
        $this->Flash->error(__('error message'));
    }

    $projekte = $this->Projekte->find('list')->where(['id !=' => $id]);
    $this->set(compact('projekt', 'projekte'));
}

In the templates like add.ctp or edit.ctp:

echo $this->Form->control('nebenprojekte._ids', ['options' => $projekte, 'multiple' => true]);

If you use another language than english, don´t forget to set the correct inflection rules. bootstrap.php:

Inflector::rules('plural', [
  '/^(projekt|nebenprojekt)$/i' => '\1e',
  '/^(projekteigenschaft)$/i' => '\1en',
]);
Inflector::rules('singular', [
  '/^(projekt|nebenprojekt)e$/i' => '\1',
  '/^(projekteigenschaft)en$/i' => '\1',
]);


Answered By - exsand3r
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, February 6, 2022

[FIXED] get relations table data is empty

 February 06, 2022     laravel, php, relationship     No comments   

Issue

i am using laravel 8. i am try to get data with many to many relationship but give me empty data for related table

it's database

enter image description here

Order Model

 public function products()
    {
        return $this->belongsToMany(Product::class);
    }

Product Model

    public function orders(): \Illuminate\Database\Eloquent\Relations\BelongsToMany
    {
        return $this->belongsToMany(Order::class);
    }

and fetch Query is

        $orders = Order::query()->with("products")->get();

Result

enter image description here

i am also check

        $orders = Order::query()->has("products")->get();

give me same result


Solution

First, if you are editing your query like this it will work

 $orders = Order::fist();
 $orders->products;

Why? becuse the pivot table.

what is the pivot table? Let me explain.

when you are working with many-to-many relations you must define an intermediate table like your table:order_prodcts. so Laravel here provides some very helpful ways of interacting with this table.

So here’s a database structure:

orders:
   - id
   - title

products:
   - id
   - title

order_product:
   - id
   - title

The final table in the list: order_product is called a pivot table

let's take your example

let's assume our Order model has many Product models that it is related to. After accessing this relationship, we may access the intermediate table using the relation method you are defining on the models like:

1-Your Product Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    //some code

    public function orders()
    {
        return $this->belongsToMany(Product::class);
    }
}

2-Your Order Model

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Order extends Model
{
    //some code

    public function produtc()
    {
        return $this->belongsToMany(Order::class);
    }
}

Here each Product model we retrieve is automatically assigned a relation method. This relation method contains a model representing the intermediate order_product table.

SO here try to get you orders with your products

public function index()
{

    $orders = Order::get();
    dd($orders->products); //Laravel will handel the pivot and will return your order products
}

Now, there are several things to mention when using pivot.

  • Pivot table fields by default should be only two fields: foreign key to each of the tables order_id product_id

  • Name of the pivot table should consist of singular names

  • Names should be arranged in alphabetical order in your case o is first of p so your table will be called order_product

Finally Thank you for finishing the read I hope you gained any information from this answer



Answered By - Abdulrahman
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Laravel where on relationship object

 February 06, 2022     eloquent, laravel, php, relationship, where-clause     No comments   

Issue

I'm developing a web API with Laravel 5.0 but I'm not sure about a specific query I'm trying to build.

My classes are as follows:

class Event extends Model {

    protected $table = 'events';
    public $timestamps = false;

    public function participants()
    {
        return $this->hasMany('App\Participant', 'IDEvent', 'ID');
    }

    public function owner()
    {
        return $this->hasOne('App\User', 'ID', 'IDOwner');
    }
}

and

class Participant extends Model {

    protected $table = 'participants';
    public $timestamps = false;

    public function user()
    {
        return $this->belongTo('App\User', 'IDUser', 'ID');
    }

    public function event()
    {
        return $this->belongTo('App\Event', 'IDEvent', 'ID');
    }
}

Now, I want to get all the events with a specific participant. I tried with:

Event::with('participants')->where('IDUser', 1)->get();

but the where condition is applied on the Event and not on its Participants. The following gives me an exception:

Participant::where('IDUser', 1)->event()->get();

I know that I can write this:

$list = Participant::where('IDUser', 1)->get();
for($item in $list) {
   $event = $item->event;
   // ... other code ...
}

but it doesn't seem very efficient to send so many queries to the server.

What is the best way to perform a where through a model relationship using Laravel 5 and Eloquent?


Solution

The correct syntax to do this on your relations is:

Event::whereHas('participants', function ($query) {
    return $query->where('IDUser', '=', 1);
})->get();

This will return Events where Participants have a user ID of 1. If the Participant doesn't have a user ID of 1, the Event will NOT be returned.

Read more at https://laravel.com/docs/5.8/eloquent-relationships#eager-loading



Answered By - Crembo
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Friday, January 28, 2022

[FIXED] Retrieve latest model belonging to a set of users from a MySQL table

 January 28, 2022     laravel, mysql, relationship, sql     No comments   

Issue

I need to retrieve the latest model in a relationship, from a collection of records that belong to a set of users. The best I've come up with is:

SELECT 
    `answers`.*,
    answers.created_at,
    `questions`.`survey_id` AS `laravel_through_key`
FROM
    `answers`
        INNER JOIN
    `questions` ON `questions`.`id` = `answers`.`question_id`
WHERE
    `questions`.`id` IN (4, 5, 6)
        AND `user_id` IN (1 , 2, 3)
group by user_id, question_id
ORDER BY `created_at` DESC

The tables are:

questions

  • id, text

answers

  • id, user_id (belongs to a user), question_id (belongs to a question)

users

  • id, name

For a set of users with IDs 1, 2, 3 - I want to retrieve the set of answers to questions with IDs 4, 5, 6 - but I only want each user's most recent answer for each question. In other words, there should only be a single answer for each user/question combination. I thought using GROUP_BY would do the trick, but I don't get the most recent answer. I'm using Laravel, but the issue is more a SQL one rather than a Laravel specific problem.


Solution

In MySQL 8 or later you can use window functions to find greatest n per group:

WITH cte AS (
    SELECT *, ROW_NUMBER() OVER (PARTITION BY user_id, question_id ORDER BY created_at DESC) AS rn
    FROM answers
    WHERE user_id IN (1 , 2, 3) AND question_id IN (4, 5, 6)
)
SELECT *
FROM cte
WHERE rn = 1


Answered By - Salman A
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Sunday, January 23, 2022

[FIXED] Laravel Relationship not working with belongsTo

 January 23, 2022     foreign-keys, laravel, model, relation, relationship     No comments   

Issue

Hello Guys, I am just passing my query to notification blade, but its gave error. I dont know what i did wrong with bellow code. If you guys fix this issue i will be very glad. Thanks in advance

Notification seen model

<?php

namespace App\Models\Backend;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class notificationseen extends Model
{
    use HasFactory;
    protected $table = 'notificationseens';

    public function Notification()
    {
        return $this->belongsTo(Notification::class, 'notificationID');
    }
}

Notification Model

<?php

namespace App\Models\Backend;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Notification extends Model
{
    use HasFactory;
    protected $table = 'notifications';

    public function notificationseen()
    {
        return $this->belongsTo(notificationseen::class, 'notificationID');
    }
}

View Blade

 @foreach( $notification as $notify )

          @if($notify->Notification->seen == 0)
          <!-- Single Notification --><a href="{{ route('singlenotify', $notify->id) }}" id="notifysee" data-id="{{ $notify->id }}">
            
            <div class="alert unread custom-alert-3 alert-primary" role="alert"><i class="bi bi-bell mt-0"></i>
              <div class="alert-text w-75">
                <h6 class="text-truncate">{{ $notify->name }}</h6><span class="text-truncate">{{ $notify->description }}</span>
              </div>
            </div></a>
          @else
          <!-- Single Notification --><a href="{{ route('singlenotify', $notify->id) }}">
          <div class="alert custom-alert-3 alert-primary" role="alert"><i class="bi bi-bell mt-0"></i>
              <div class="alert-text w-75">
              <h6 class="text-truncate">{{ $notify->name }}</h6><span class="text-truncate">{{ $notify->description }}</span>
              </div>
            </div></a>

          @endif
        @endforeach 

Table structure

 $table->increments('id');
            $table->integer('userid');
            $table->integer('notificationID');
            $table->integer('seen')->default('0')->comment("0 for unseen 1 for seen");
            $table->timestamps();

Can you please help me out. I cant see any issue but its me error "Attempt to read property "seen" on null"


Solution

You can try to add an isset to avoid the error :

@if(isset($notify->Notification->seen) && $notify->Notification->seen == 0)
   (...)
@else
   (...)
@endif

EDIT : in your code, you defined 2 belongsTo methods, but according to the official Laravel documentation, you must define a hasOne method and the inverse of it, the belongsTo method.



Answered By - Jérôme
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Saturday, January 8, 2022

[FIXED] Laravel orderBy on a relationship

 January 08, 2022     laravel, laravel-4, php, relationship     No comments   

Issue

I am looping over all comments posted by the Author of a particular post.

foreach($post->user->comments as $comment)
{
    echo "<li>" . $comment->title . " (" . $comment->post->id . ")</li>";
}

This gives me

I love this post (3)
This is a comment (5)
This is the second Comment (3)

How would I order by the post_id so that the above list is ordered as 3,3,5


Solution

It is possible to extend the relation with query functions:

<?php
public function comments()
{
    return $this->hasMany('Comment')->orderBy('column');
}

[edit after comment]

<?php
class User
{
    public function comments()
    {
        return $this->hasMany('Comment');
    }
}

class Controller
{
    public function index()
    {
        $column = Input::get('orderBy', 'defaultColumn');
        $comments = User::find(1)->comments()->orderBy($column)->get();

        // use $comments in the template
    }
}

default User model + simple Controller example; when getting the list of comments, just apply the orderBy() based on Input::get(). (be sure to do some input-checking ;) )



Answered By - Rob Gordijn
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Laravel - Retrieve foreign table name

 January 08, 2022     eloquent, foreign-keys, laravel, relationship     No comments   

Issue

I got and issue with relationships between simple data in a small laravel project.

I have a recipes table that list recipes, and I got a recipe_types table listing the type of recipe. In my recipes table, I got a column recipe_types_id that is a foreign key referring to the id column of the recipe_types table.

In Laravel, I have a view, where I want to list all the recipes, where I show the Recipe Name and the Recipe Type name.

A recipe can only have 1 type, but a type can be linked to multiple recipes.

Now in the Recipe model I added this:

public function recipeType()
{
   return $this->hasOne(RecipeType::class,'id');
}

I am pretty sure that the relationship hasOne is the right one, but because of the issue I have, I start having doubts.

and in my RecipeController, I retrieve all the post like this :

public function index()
{
    $recipes = Recipe::with('recipeType')->get();

    return view('recipes')->with('recipes', $recipes);
}

The issue I have right now, it's that when I display in my blade view the Recipe of ID 1 (with a recipe_type_id of 3), when I Use {{ $recipe->recipeType->name }}, that return the name of the recipe_type with the ID 1 and not the recipe_type with the ID 3.

Here example of the data, current behavior and expected behavior :

=== Recipe Table ===
{id: 1, name: 'Chocolate Cake', recipe_type_id: 3},
{id: 2, name: 'Carrot soup', recipe_type_id: 1}

=== Recipe Type Table ===
{id: 1, name: 'Soup'},
{id: 2, name: 'Main plate'},
{id: 3, name: 'Dessert'}

In my listing what I got now (the type ID retrieved is the ID of the Recipe):

  • Recipe 1
    • Name: Chocolate Cake
    • Type: Soup
  • Recipe 2
    • Name: Carrot soup
    • Type: Main plate

In my listing what I want and should have :

  • Recipe 1
    • Name: Chocolate Cake
    • Type: Dessert
  • Recipe 2
    • Name: Carrot soup
    • Type: Soup

Have you an idea of what I have been missing? I read the documentation, look on google and here on StackOverflow, I found solutions that I thought would help me, but they didn't, and I become frustrated not been able to complete what should be simple I think(?)

Thank you very much for your help.


Solution

In your case, you have Recipe which belongs to one RecipeType.

Try like this:

public function recipeType()
{
   return $this->belongsTo(RecipeType::class, 'recipe_types_id', 'id');
}

In the docs you can imagine your model RecipeType as Post and Recipe as Comment.

Recipe belongs to only one RecipeType, RecipeType can have many Recipe.

I hope I helped you to understand.



Answered By - mare96
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, December 30, 2021

[FIXED] yii hasone relation with condition

 December 30, 2021     activerecord, relationship, yii, yii2     No comments   

Issue

I have a hasone relation in my code,

public function getDevice(){
    return $this->hasOne(UserDevice::className(),['user_id' => 'id'])->where(['is_latest'=>true]);
}

In my query, I am trying to fetch user details.

  $query = User::find();
  $query->joinWith('device')->all();

If i am using getDevice without where condition, I am getting all users. But if I add where condition inside getDevice, I am getting users that have device details. Is there anyway to list all users with the chceking. That is I need to list all users, who has either details in device table or not


Solution

I have used this in my relation and it works.

public function getDevice(){
    return $this->hasOne(UserDeviceInfo::className(),['user_id' => 'id'])->orOnCondition(['is_latest' =>1]);
}


Answered By - reshma
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing