FuelPHP ORM find('all') get only one row - php

When i use FuelPHP ORM to get ALL results using find('all'), it's return only one record.
This is my db.
table name ws_config. (no primary key)
--------------------------
config_name | config_value |
--------------------------
site_name | My Site |
--------------------------
member_allow_register | 1 |
--------------------------
This is my model.
class Model_Config extends Orm\Model
{
protected static $_table_name = 'config';
protected static $_primary_key = array();// no PK, need to set PK to empty array.
}
This is my controller
class Controller_Account_Register extends \Controller_Basecontroller
{
public function action_index()
{
$config = Model_Config::find('all');
$output['config'] = $config;
// call function below is in base controller. it is just load theme (this view page into main template) nothing special.
return $this->generatePage('front/templates/account/register_v', $output);
}
}
This is my view file.
foreach ($config as $row) {
//print_r($row);
echo $row->config_name;
echo ' = ';
echo $row->config_value;
echo '<br>';
}
The result is just
site_name = My Site
How to get ALL results from this database table? or
How to get multiple results upon where ondition?

The issue here is that indeed as #vee says the ORM expects you to have a primary key assigned to your table. By default in the orm this is simply a column called "id". If you do not specify a PK unexpected behaviour happens, such as this.
Once you define a primary key on your table this issue should be resolved.
The simplest thing would be to just add an auto-incrementing ID column as this is the default for orm models.

FuelPHP ORM needs Primary key to get ALL results.
No PK you can get only one result.
erm... :(

Related

Laravel Model Relationship on Non-Static Tables

So, I have a legacy Database, with a poorly designed structure that has recently been moved to Laravel, but with some hacky nonsense to get it to work with models. Given the following Tables:
|==========================|====|============|===========|
| companies | id | token | name |
|--------------------------|----|------------|-----------|
| people_{companies.token} | id | first_name | last_name |
|==========================|====|============|===========|
The companies table contains multiple records, with an auto-incrementing ID, unique token, and name.
Each Company has its own people_{companies.token} table, instead of a single people table, with an associated client_id.
At first, this meant I couldn't use a standard Company and Person Model/Relationships, as protected $table needs to be static. We got around this with a DynamicBinding Trait:
<?php
namespace App\Models\Traits;
trait DynamicBinding {
protected $connection = null;
protected $table = null;
public function bind(string $connection, string $table) {
$this->setConnection($connection);
$this->setTable($table);
}
public function newInstance($attributes = [], $exists = false) {
$model = parent::newInstance($attributes, $exists);
$model->setTable($this->table);
return $model;
}
}
This allows for setting a table on the fly:
$company = Company::first();
$people = (new Person())->setTable("people_{$company->token}");
$person = $people->first();
This works perfectly fine, returning the first record from the people_{$company->token} table, and facilitating most functionality required. Now, I'd like to make this work with Relationships. Given the following example:
// Person.php
public function company() {
return $this->belongsTo(Company::class);
}
$company = Company::first();
$people = (new Person())->setTable("people_{$company->token}");
$person = $people->first(); // No Issue
$peopleWithCompany = $people->with('company')->first(); // Cannot find table `people`
This returns the error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'database.people' doesn't exist (SQL: select * from people limit 1)
Essentially, as soon as ->with() (or other functions, like ->query(), etc) is appended, it tries to perform the query based on the determined table (people from Person) instead of the table set via $people->setTable().
Does anyone have any experience connecting models to this kind of data structure, while allowing use of Eager Loading with Relationships? And sidenote, there is a plan to migrate everything to a single people table, but unfortunately not anytime soon...
Thanks in advance!

Eloquent ORM Many-to-many relationship

I've just started using Eloquent ORM (Without Laravel) and I am having issues with the many to many relationships.
I have a table where I store Families (Article categories), another one for the Articles, and a third one as a "pivot". I want to be able to get all the articles a Family has, and all the families an article belongs to. So I have coded this models.
Families
class Families extends Model {
public $table = 'Families';
public function Articles() {
return $this->belongsToMany('Articles', 'articles_families', 'families_id', 'articles_id');
}
}
Articles
class Articles extends Model {
public $table = 'Articles';
public function Families() {
return $this->belongsToMany('Families', null, 'articles_id', 'families_id');
}
}
Then I am trying to retrieve the data like this:
$families = Families::all();
echo $families[1]->Articles;
However, it just returns an empty array, when it should return a couple of articles. I have tripled checked that all the values are correct in the three tables. If I echo the Eloquent query debugger I can see that it is looking for a null value and I'm pretty sure that's the problem, but I don't quite know how to fix it. Here:
{"query":"select * from `Families`","bindings":[],"time":49.13},{"query":"select `Articles`.*, `articles_families`.`families_id` as `pivot_families_id`, `articles_families`.`articles_id` as `pivot_articles_id` from `Articles` inner join `articles_families` on `Articles`.`id` = `articles_families`.`articles_id` where `articles_families`.`families_id` is null","bindings":[],"time":38.93}
The null value is at the end of the last query.
I just found the solution myself. As my primary key columns are called Id, and Eloquent by default assumes the primary key is called id, I needed to override that by adding a class property protected $primaryKey = "Id"; and it now retrieves the data properly.

Creating self referencing relationships

I want to be able to make relationships between a captain and his referrals. They both belong to the same table. I have this in my model
public function captain() {
$this->belongsTo('User', 'referral_id') ;
}
public function captain() {
$this->hasMany('User', 'referral_id') ;
}
My users table has the following columns
id name referral_id referred_by
1 xyz 1223 null
2 Abc 4525 1223
How do I create the relationship better? And I want to know if I can and how I can use this to get the referral of a referral of the captain
I'd create a second table for your referrals - then you create a relationship between your captain ID in table 1 over in table 2 where all the referers can be stored. If you setup the relationship, you then simply call something like
$captains = App\Captain::all();
foreach ($captains as $captain) {
echo $captain->referrals->name;
}
ref
using simple eager loading... or ->with using other methods (or join etc)

Symfony, Doctrine, how do I load all the data in a join but also load the data row with columns that have no data?

I apologize if the question doesn't make any sense. So essentially I have 3 tables, table One, Two, and Three that are linked together. Table One is OneToMany relationship with table Two, and table Two has OneToMany Relationship with table Three.
The tables have the following columns:
One
id | package_no | weight | dimensions
Two
id | one_id | rack_no | part_no | batch_no
Three
id | two_id | datein | dateout
So only some of these data have a dateout from table Three since it is optional. When I list the data from table One and Two and Three, Doctrine is only distinctly listing the rows that have a dateout. I want it to list all the rows even when it doesn't have a dateout, and have that table cell as empty.
This is what I tried:
$pkg = $em->getRepository('Bundle:Two')
->findInventoryByPkgno($packageNo);
I first tried by doing a query that grabs the data by package_no and it will give me the data from table One and Two, and then I did a for loop to grab each two_id to get the data from table Three.
for($i=0;$i<count($pkg);$i++) {
$twoid = $pkg[$i]['packageNo'];
$getthree = $em->getRepository('Bundle:Three')
->findOneByTwoId($twoid);
}
But then I realized when I output it to twig, it is just going to list only one result...
Is this possible?
do you have configured the mapped/inversed in the entity ?
ONE:
/**
* #ORM\OneToMany(targetEntity="Two",mappedBy="one",cascade={"persist","remove"})
*/
private $twos;
public function __construct()
{
$this->twos = new ArrayCollection();
}
public function getTwos()
{
return $this->twos;
}
and two:
/**
* #ORM\ManyToOne(targetEntity="One",inversedBy="twos")
*/
private $one;
public function getOne(){
return $this->one;
}
and the controller yo can do:
$ones = $em->getRepository('Bundle:One')->findAll();
foreach($ones as $one){
foreach($one->getTwos() as $two){
//Access entity $two
}
}

Laravel 4 - Models & One to Many

I'm trying to get my head around laravel models & one to many...
I have the following tables
ww_bookings
-----------------------------
booking_id
customer_id
quote_id
ww_quotes
-----------------------------
quote_id
etc
etc
etc
I'm using sentry for my auth and basically on a sucsessful login I want to find the id of the logged in user and then query the ww_bookings data WHERE customer_id = 'logged in user id'.
Once it's good all the bookings for the customer_id it then need to go and query ww_quotes for each booking found and bring back the data.
//Controller
BookingData::find(1)->quotes()->where('quote_id', '=', '1')->get();
//BookingData Model
class BookingData extends Eloquent {
protected $table = 'ww_bookings';
protected $primaryKey = 'customer_id';
public function quotes() {
return $this->hasMany('QuoteData');
}
}
//QuoteData Model
class QuoteData extends Eloquent {
protected $table = 'ww_quotes';
}
I get the following error:
Column not found: 1054 Unknown column 'ww_quotes.booking_data_id' in 'where clause' (SQL: select * from ww_quotes where ww_quotes.booking_data_id = 1 and quote_id = 1)
Can anyone help me out, it's been driving me crazy...
Hope it makes sense..
There are two problems I see:
Wrong relationship
The problem is that ww_quotes schema/table should contain key that refers ww_booking schema/table - exactly in reverse.
Solution to this:
ww_bookings
-----------------------------
customer_id
quote_id
ww_quotes
-----------------------------
quote_id
booking_id
Key will not match
Key names that Eloquent generates and uses for relations will not match existing key names. If you specify them, Eloquent use them instead.
return $this->hasMany('QuoteData', 'booking_id');

Categories