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

Friday, October 21, 2022

[FIXED] How to set up a has-many relationship in Cocoa?

 October 21, 2022     has-many, iphone, key-value-coding, objective-c, one-to-many     No comments   

Issue

I'm building a (very) simple FTP app in Cocoa, and I need to store information on the different types of servers that are supported. So, I've created a ServerType class, which stores all of the relevant information about a single type of server. I then have a ServerTypes class which is designed to manage all of the ServerType classes that are created.

My question is, how to set up the relationship between the two objects. Is there a preferred method to do so?

Also, since Objective-C doesn't support non-instance classes, where should I create an instance of ServerTypes that will have to be used throughout the entire program? Or is there a better way to do that? I need it to be KVC compliant so That I can bind one of the ServerType properties to an NSPopupBox.

I'm fairly new to Cocoa and Objective-C.


Solution

To manage a relationship between 2 objects, you have 2 ways: composition or inheritance.

You can inherit from a class to create a subclass then you will have a is-a relationship.

If one object contains another as an instance variable then you will have a has-a relationship.

Here, I think it would be the best to use composition where the ServerTypes objects has an array of all server type objects. Objective-C supports non-instance variable (if that's what you mean), by creating static variable. Then you can use it accross the whole program



Answered By - vodkhang
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Tuesday, March 8, 2022

[FIXED] Many to One relationship?

 March 08, 2022     mysql, one-to-many, php, yii     No comments   

Issue

The following MySQL code...

CREATE TABLE Employee (
    id MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY,
    departmentId TINYINT UNSIGNED NOT NULL
        COMMENT "CONSTRAINT FOREIGN KEY (departmentId) REFERENCES Department(id)",
    firstName VARCHAR(20) NOT NULL,
    lastName VARCHAR(40) NOT NULL,
    email VARCHAR(60) NOT NULL,
    ext SMALLINT UNSIGNED NULL,
    hireDate TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    leaveDate DATETIME NULL,
    INDEX name (lastName, firstName),
    INDEX (departmentId)
)

CREATE TABLE Department (
    id TINYINT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY, 
    name VARCHAR(40),
    UNIQUE (name)
)

... defines a many to one relationship between an employee and a department. In other words, an employee can only be in one department, but a department can have many employees. But can someone explain this in more detail? How does the above code tell me that?


Solution

It is sometimes easy to discern the relationship between two (or more) tables by looking at the foreign key of referring table.

A simple rule is, if the foreign key is a primary key itself in its own table, the relationship is probably 1 to 1, whereas if the foreign key is not a primary key in its own table, the relationship is probably 1 to many, where the table having the foreign key at the "many" end.

In your example, for departmentID in Employee, it is not a primary key. Therefore, in this situation, a Department can be referenced by a lot of Employees at the same time, hence the "1 to many" relation can be established.

However, in your quoted example from mkyong.com, both tables (stock and stock_detail) use stock_id as primary key. In this situation, the "1 to 1" relation can be established.

Consider this: Both stock and stock_detail tables will only contain ONE single record having a certain value as stock_id. I made a sample here.



Answered By - Amao Mao
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

Thursday, February 17, 2022

[FIXED] Laravel One-To-Many insertion on a Pivot table

 February 17, 2022     eloquent, laravel, laravel-5.3, one-to-many, php     No comments   

Issue

I am using Laravel 5.3 ad having issues on saving through the hasMany relationship.

I have tables employee and activity which has One-to-Many Relation i.e Each employee will perform many activities.

When I am adding activities against employee using associate() it send me an error:

BadMethodCallException in Builder.php line 2440:
Call to undefined method Illuminate\Database\Query\Builder::associate()

Below are the DB structure and code:

Database structure:

employee (1st table)
– employee_id
– employee_name
- created_at
- updated_at

activity (2nd table)
– activity_id
– activity_name
- created_at
- updated_at

employee_activity (pivot table)
– employee_activity_employee_id
– employee_activity_activity_id

Model Class Employee:

class Employee extends Model
{
    protected $table = 'employee';
    protected $primaryKey = 'employee_id';

    public function activity() {
        return $this->hasMany('App\Models\Activity', 'employee_activity', 'employee_activity_employee_id', 'employee_id');
    }
}

Model Class Activity:

class Activity extends Model
{
    protected $table = 'activity';
    protected $primaryKey = 'activity_id';

    public function employee() {
        return $this->belongsTo('App\Models\Employee', 'employee_activity', 'employee_activity_activity_id' ,'activity_id');
    }
}

Controller:

public function EmployeeActivityAssociation()
{
    $employee_id = Input::get('employee_id');
    $activity_ids = Input::get('activity_id'); // This is an array of activities
    $employee = Employee::find($employee_id);
    if (!empty($employee)) {
         //Adding activity under the employee
        foreach ($activity_ids as $id) {
            $activity = Activity::find($id);
            $employee->activity()->associate($activity);
            $employee->save();
        }
        return 'Activities asscoiated to employee';
    }   
    else {
        return 'Employee not found';
    }
}

Do I have my relationship defined incorrectly here?


Solution

Your relation is not defined correctly. By seeing your table structure it should be many-to-many relationship.

Model Class Employee:

public function activity() {
    return $this->belongsToMany('App\Models\Activity', 'employee_activity', 'employee_activity_employee_id', 'employee_id');
}

Model Class Activity:

public function employee() {
    return $this->belongsToMany('App\Models\Employee', 'employee_activity', 'employee_activity_activity_id' ,'activity_id');
}

SO your controller should be as:

public function EmployeeActivityAssociation()
{
    $employee_id = Input::get('employee_id');
    $activity_ids = Input::get('activity_id'); // This is an array of activities
    $employee = Employee::find($employee_id);
    if (!empty($employee)) {
        $employee->activity()->attach($activity_ids);
      return 'Activities asscoiated to employee';
    }   
    else {
        return 'Employee not found';
    }
}

If you want to stick to one-to-many relation then you have to change your table schemas as:

Remove table employee_activity table and add column employee_id in activity table then define relation according to one-to-many.



Answered By - Amit Gupta
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