Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

131
Vistas
Laravel Eloquent - Many to One Relation

I have Models: ArtObjects and Photos:

class Photo extends Model
{
    protected $fillable = ['caption','description','alternative_text'];

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

class ArtObject extends Model
{

    /**
     * The attributes that are mass assignable.
     *
     * @var array
     */
    protected $fillable = [
        'title',
        'description',
        'rating',
        'popularity',
        'type',
        'price'
    ];

    public function photos()
    {
        return $this->hasMany(ArtObjectPhoto::class);
    }
}

Controllers:

ArtObject Controller:

public function store(ArtObjectUploadRequest $request)
{
    $art_object = ArtObject::create(request(['title', 'description', 'rating', 'popularity', 'type', 'price']));

    $this->validate($request, [
        'title' => 'required',
        'description' => 'required'
    ]);

    foreach ($photo_ids = Input::get('photos') as $photo_id) {

        $photo = Photo::find($photo_id);

        /*
        Problem is here - The user wants to attach the selected photos with
        the art-object, ........ Please advise, thanks in anticipation !!!
        */  

    }

    //save the artobject to the database
    $art_object->save();

    //And redirect to the home page
    return redirect('/');
}

Problem: The user wants to attach the selected photos with the art-object. Note that the photos already exists in the db. I have tried options - save(), associate () but nothing helped. My understanding is once I find () the photo it should give me Photo object which I should be able to save () with $art_object. It wants me to new() and assign from DB and assign to the Photo object. But I don't think this is the right way of doing this. I believe this is not the best way of implementing the many-to-relation , then what is the best way saving this relation. Please advise, thanks in anticipation !!!

about 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

According to Many to One Relationship Rule in Database,the Foreign key connecting the tables is always saved in the table which has "many" relation.

Like here,One ArtObject can have many Photos.So,That "Many" table is Photos. Your Photo Model must have an attribute named art_object_id as a Foreign key.

Then you have to save that ArtObject object first and save this object's id in the photos table in all those rows whose id is selected by the user.

$art_object = ArtObject::create(request(['title', 'description', 'rating', 'popularity', 'type', 'price']));

$this->validate($request, [
    'title' => 'required',
    'description' => 'required'
]);

 //save the artobject to the database
$art_object->save();

foreach ($photo_ids = Input::get('photos') as $photo_id) {

    $photo = Photo::find($photo_id);
    $photo->art_object_id = $art_object->id;
    $photo->save();


 }

After doing this ,you can fetch the related ArtObject of a photo by the method you defined in the Photo model to relate ArtObject and Photo tables together.You can also fetch the photos related to an ArtObject by the defined method in ArtObject.

In ArtObject Model:-

 public function photos()
{
    return $this->hasMany('App\Photo');
}

In Photo Model:-

 public function artObject()
{
    return $this->belongsTo('App\ArtObject');
}
about 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda