Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

132
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda