-
Notifications
You must be signed in to change notification settings - Fork 53
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Como fazer JOIN entre duas ou mais tabelas #72
Comments
pelo que entendi, você faz o relacionamento pelas próprias classes modelo. Exemplo: Quero pegar os dados do usuário que está na tabela "users", mas também quero pegar o endereço deste mesmo usuário que está em outra tabela chamada "addresses". você poderia fazer algo assim: User.php: namespace App\Models;
use CoffeeCode\DataLayer\DataLayer;
class User extends DataLayer {
public function __construct()
{
parent::__construct("users", []);
}
} Address.php: namespace App\Models;
use CoffeeCode\DataLayer\DataLayer;
class Address extends DataLayer {
public function __construct()
{
parent::__construct("addresses", []);
}
} index.php: require_once __DIR__ . '/../vendor/autoload.php';
use App\Models\Address;
use App\Models\User;
$userId = 1;
$user = (new User)->findById($userId);
$address = (new Address)->findById($user->id_address);
echo "{$user->name}, está morando na rua {$address->street}"; Tabelas:CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
id_address INT,
name VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
CREATE TABLE addresses (
id INT AUTO_INCREMENT PRIMARY KEY,
street VARCHAR(255) NOT NULL,
neighborhood VARCHAR(255) NOT NULL,
created_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
updated_at TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);
|
No exemplo do colega eu faço join assim: User.php: namespace App\Models;
use CoffeeCode\DataLayer\DataLayer;
use App\Models\Address;
class User extends DataLayer {
public function __construct()
{
parent::__construct("users", []);
}
public function address() {
return (new Address())->findById($user->id_address);
}
} Index.php require_once __DIR__ . '/../vendor/autoload.php';
use App\Models\Address;
use App\Models\User;
$userId = 1;
$user = (new User())->findById($userId);
echo "{$user->name}, está morando na rua {$user->address()}"; Pode ser que haja um jeito melhor, mas é assim que eu faço =D |
Uso esse componentes mas até hoje não entendi como fazer um JOIN entre duas ou mais tabelas, alguém poderia dar um exemplo melhor do que tem na descrição do componente ?
The text was updated successfully, but these errors were encountered: