I have this code and wonder get the methods properties values.
<?php
class framework{
// users table
function users(){
$username="VARCHAR (255)";
$email="VARCHAR (255)";
$password="VARCHAR (255)";
}
// product table
function produts(){
$title="VARCHAR (255)";
$price="INT ()";
$author="VARCHAR (255)";
}
//categories table
function categories(){
$category_name="VARCHAR (255)";
}
}
?>
I'm trying to create my own framework and in this particular code I'm trying to simplify database creation. The idea is to get the class name as the database name and the methods as tables names, and the last get the methods properties as cols.
I use get_class() to get the class name and add as table name;
get_class_methods to get the class methods and create the table.
So I have no idea of how to create the respective cols.
I am not recommending this approach because you are reinventing the wheel here, but you could expose your DDL info via public properties. Of course, you can make these private/protected and expose them via getters.
I also created a base model which your child models can inherit. This allows for IDE autocompletion in the DatabaseBuilder below.
<?php
namespace Bartolomeu;
// Base model
abstract class Model {
public $table;
public $columns;
}
class User extends Model
{
public $table = 'users';
public $columns = [
'username' => 'VARCHAR (255)',
'email' => 'VARCHAR (255)',
'password' => 'VARCHAR (255)',
];
}
class Product extends Model
{
public $table = 'products';
public $columns = [
'title' => 'VARCHAR (255)',
'price' => 'INT ()',
'author' => 'VARCHAR (255)',
];
}
class Category extends Model
{
public $table = 'categories';
public $columns = [
'category_name' => 'VARCHAR (255)',
];
}
Finally, you can create a class that will actually "read" the models and do the necessary work to create the tables themselves.
<?php
class DatabaseBuilder
{
public function createTables()
{
$models = [
new User(),
new Product(),
new Category(),
];
foreach ($models as $model) {
/* #var Model $model */
$table = $model->table;
$columns = $model->columns;
//...
}
}
}
Related
I have this given table structure:
How can I access the 'curso.name' from my 'visita' class using eloquent?
I assigned the many to many relationships but can only access the 'turma.curso_id', but I wanna get something like $visita->curso['nome'].
I wanna know how to avoid needing Curso::all().
Added some snippets below:
// Class VISITA
class Visita extends Model
{
protected $fillable = [
'id',
'nome',
];
public function turmas()
{
return $this->belongsToMany('App\Models\Turma', 'turma_disciplina_visita')->withPivot('disciplina_id');
}
}
// Class TURMA
class Turma extends Model
{
protected $fillable = [
'id',
'nome',
'curso_id',
];
public function curso()
{
return $this->belongsTo('App\Models\Curso');
}
}
// Class CURSO
class Curso extends Model
{
protected $fillable = [
'id',
'nome',
];
public function turmas()
{
return $this->hasMany('App\Models\Turma');
}
}
// Class VISITACONTROLLER
class VisitaController extends BaseController
{
public function list($request, $response)
{
$visitas = Visita::all(); // brings me the visita and the turma with its attributes
$cursos = Curso::all(); // wanted to get cursos without needing this extra query which brings me all the cursos..
return $this->view->render($response, 'Visitas/list.php', [
'visitas' => $visitas,
'cursos' => $cursos,
]);
}
}
// View LIST.PHP
// This way I get the turma.nome
foreach ($visita->turmas as $turma){
echo $turma['nome'] . '<br>';
// This way I get the curso.nome
foreach ($visita->turmas as $turma){
echo $cursos[$turma['curso_id']] . '<br>';
have you tried to load your collection like this:
Visita::with('turmas.curso')->all();
And in your frontent you should be able to load your data like this:
foreach (($visita->turmas as $turma){
$turma->curso->nome;
}
Hope this helps
I would like to add some items in my db table pivot using eloquent ->attach but i don' t understand why it don't work:
I have 2 models (Salade=>(table 'salades' in DB) and Ingredient=>(table 'ingredients' in DB),
the pivot table is ingredient_salade( 3columns : id, ingredient_id,salade_id).
My Models:
class Ingredient extends Model
{
protected $table = 'ingredients';
protected $fillable = ['nom'];
public function Salades()
{
return $this->belongsToMany('App\Salade');
}
}
class Salade extends Model
{
protected $table = 'salades';
protected $fillable = ['nom','prix'];
public function ingredients()
{
return $this->belongsToMany('App\Ingredient');
}
}
SaladeController#Store
public function store(Request $request)
{
$this->validate($request, [
'nom' => 'required',
'prix' => 'required' ]);
$salade = $request->only(['nom', 'prix']);
// insert new salade in DB
$lanouvelleSalade = \App\Salade::create($salade);
//insert relation in pivot table
$lanouvelleSalade->ingredients()->attach([21,22,23]);
return redirect('salade')->withOk("Le Salade " . $request->input('name') . " a été modifié.");
}
the tables:
image of the tables
the new salade is insert in table salades but the relation in Pivot is not insert. Why?
change:
$lanouvelleSalade->ingredients()->attach([21,22,23]);
to:
$lanouvelleSalade->ingredients()->sync([21,22,23]);
replace your relation codes with this codes and check it:
Ingredient Class:
public function Salades()
{
return $this->belongsToMany('App\Salade','ingredient_salade','ingredient_id','salade_id');
}
And Salade Class:
public function ingredients()
{
return $this->belongsToMany('App\Ingredient','ingredient_salade','salade_id','ingredient_id');
}
let me know if you have any error
I've been trying to wrap my head on figuring out how to update my hasMany relationship model. I can easily create new relationships but when I try to update my relationship model it does not work? Does laravel push() method still work? Can anyone help please? For example I want to update my Taxonomy Table thats related to my Products table within my Controller. I have a code snippet below::
Product.php
class Product extends Model
{
protected $fillable = [
'product_category', 'product_subcategory', 'product_name',
'product_price', 'product_id', 'product_description', 'product_image'
];
protected $primaryKey = 'product_id';
public $incrementing = false;
public function addTaxonomiesToProduct()
{
return $this->hasOne('App\Taxonomies', 'product_id', 'product_id');
}
}
Taxonomies.php
class Taxonomies extends Model
{
protected $fillable = ['product_category', 'product_subcategory'];
protected $primaryKey = 'product_id'; // or null
public $incrementing = false;
public function product()
{
return $this->belongsTo(Product::class);
}
}
EditProductController.php
class EditProductController extends Controller
{
public function update(Request $request, Product $product)
{
$product_size = array();
foreach ($request->product_size as $key => $value)
{
array_push($product_size,$value);
}
$product->update([
'product_name' => $request->product_name,
'product_price' => $request->product_price,
'product_description' => $request->product_description,
'product_size' => serialize($product_size),
'product_image' => $product_image_path,
]);
/**
* Go the products table,
* Get the product based off its product_id,
* and then update this products taxonomy
**/
$taxonomies = Product::find($product->product_id);
$taxonomies->addTaxonomiesToProduct->product_subcategory = "Mens Shoes";
$taxonomies->push();
}
}
****Update Issued Solved****
By changing hasMany() to hasOne() within my Products table, my taxonomies table updated correctly.
I think you don't fully understand the way Laravel Eloquent relationships work. First off, you need to define the relationship in both models.. Your Taxonomy model has this, but your Product model should have:
public function taxonomies()
{
return $this->hasMany('App\Taxonomies', 'product_id', 'product_id');
}
Then to update a Product's taxonomies, you'd have something like...Uh, I'm not sure what you're trying to achieve here, especially with the way you chained the product_subcategory, so I can't rightly say, but do see the documentation
I've got 2 models with a many-to-many relationship. I want to be able to set a specific attribute with an array of ids and make the relationship in the mutator like this:
<?php
class Profile extends Eloquent {
protected $fillable = [ 'name', 'photo', 'tags' ];
protected $appends = [ 'tags' ];
public function getTagsAttribute()
{
$tag_ids = [];
$tags = $this->tags()->get([ 'tag_id' ]);
foreach ($tags as $tag) {
$tag_ids[] = $tag->tag_id;
}
return $tag_ids;
}
public function setTagsAttribute($tag_ids)
{
foreach ($tag_ids as $tag_id) {
$this->tags()->attach($tag_id);
}
}
public function tags()
{
return $this->belongsToMany('Tag');
}
}
<?php
class Tag extends Eloquent {
protected $fillable = [ 'title' ];
protected $appends = [ 'profiles' ];
public function getProfilesAttribute()
{
$profile_ids = [];
$profiles = $this->profiles()->get([ 'profile_id' ]);
foreach ($profiles as $profile) {
$profile_ids[] = $profile->profile_id;
}
return $profile_ids;
}
public function profiles()
{
return $this->belongsToMany('Profile');
}
}
However the setTagsAttribute function isn't working as expected. I'm getting the following error: SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'profile_id' cannot be null (SQL: insert intoprofile_tag(profile_id,tag_id) values (?, ?)) (Bindings: array ( 0 => NULL, 1 => 1, ))
You can't attach many-to-many relations until you've saved the model. Call save() on the model before setting $model->tags and you should be OK. The reason for this is that the model needs to have an ID that Laravel can put in the pivot table, which needs the ID of both models.
It looks like you're calling the function incorrectly or from an uninitialized model. The error says that profile_id is NULL. So if you're calling the function as $profile->setTagsAttribute() you need to make sure that $profile is initialized in the database with an ID.
$profile = new Profile;
//will fail because $profile->id is NULL
//INSERT: profile->save() or Profile::Create();
$profile->setTagsAttribute(array(1,2,3));
Additionally, you can pass an array to the attach function to attach multiple models at once, like so:
$this->tags()->attach($tag_ids);
You can also pass it the model instead of the ID (but pretty sure array of models won't work)
Try using the sync method:
class Profile extends Eloquent {
protected $fillable = [ 'name', 'photo', 'tags' ];
protected $appends = [ 'tags' ];
public function getTagsAttribute()
{
return $this->tags()->lists('tag_id');
}
public function setTagsAttribute($tag_ids)
{
$this->tags()->sync($tagIds, false);
// false tells sync not to remove tags whose id's you don't pass.
// remove it all together if that is desired.
}
public function tags()
{
return $this->belongsToMany('Tag');
}
}
Don't access the tags through the tags() function, rather use the tags property. Use the function name if you want to pop additional parameters onto the relationship query and the property if you just want to grab the tags. tags() works in your getter because you're using get() on the end.
public function setTagsAttribute($tagIds)
{
foreach ($tagIds as $tagId)
{
$this->tags->attach($tagId);
}
}
Given the following, very simple, example:
Country Class
class Country extends Eloquent {
protected $table = "countries";
protected $fillable = array(
'id',
'name'
);
public function state() {
return $this->hasMany('State', 'country_id');
}
}
State Class
class State extends Eloquent {
protected $table = "states";
protected $fillable = array(
'id',
'name',
'country_id' #foreign
);
public function country() {
return $this->belongsTo('Country', 'country_id');
}
}
How can I list all the states, based on the id or the name of the country.
Example:
State::with('country')->where('country.id', '=', 1)->get()
The above returns an area, as country is not part of the query (Eloquent must attach the join later, after the where clause).
I think you're either misunderstanding the relations or over-complicating this.
class Country extends Eloquent {
public function states() {
return $this->hasMany('State', 'state_id');
}
}
$country = Country::find(1);
$states = $country->states()->get();